Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 121 additions & 2 deletions lib/components/AsyncBlock/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('<AsyncBlock />', () => {

afterEach(() => {
vi.restoreAllMocks()
vi.useRealTimers()
})

it('should render pending state', () => {
Expand Down Expand Up @@ -219,7 +220,6 @@ describe('<AsyncBlock />', () => {
})

expect(onError).not.toHaveBeenCalled()
vi.useRealTimers()
})

it('should call reload when pending function is called', async () => {
Expand Down Expand Up @@ -270,7 +270,6 @@ describe('<AsyncBlock />', () => {
})

expect(onError).not.toHaveBeenCalled()
vi.useRealTimers()
})

it('should not update state if aborted due to dependency change (race condition)', async () => {
Expand Down Expand Up @@ -357,4 +356,124 @@ describe('<AsyncBlock />', () => {
// It should render nothing
expect(container.firstChild).toBeNull()
})

it('should clear timeout if promise resolves before timeout', async () => {
vi.useFakeTimers()
const spy = vi.spyOn(global, 'clearTimeout')

let resolvePromise: (val: string) => void
const promise = new Promise<string>((resolve) => {
resolvePromise = resolve
})

render(
<AsyncBlock
promiseFn={() => promise}
pending="Loading"
success={(data) => <div>{data}</div>}
timeOut={1000}
/>,
)

await act(async () => {
resolvePromise!('Success')
})

expect(spy).toHaveBeenCalled()
spy.mockRestore()
})

it('should clear timeout if promise rejects before timeout', async () => {
vi.useFakeTimers()
const spy = vi.spyOn(global, 'clearTimeout')

let rejectPromise: (reason?: unknown) => void
const promise = new Promise<string>((_, reject) => {
rejectPromise = reject
})

render(
<AsyncBlock
promiseFn={() => promise}
pending="Loading"
success={() => 'Success'}
error={() => 'Error'}
timeOut={1000}
/>,
)

await act(async () => {
rejectPromise!(new Error('Failed'))
})

expect(spy).toHaveBeenCalled()
spy.mockRestore()
})

it('should not call onError if unmounted before promise rejects', async () => {
const onError = vi.fn()
let rejectPromise: (reason?: unknown) => void
const promise = new Promise<string>((_, reject) => {
rejectPromise = reject
})

const { unmount } = render(
<AsyncBlock
promiseFn={() => promise}
pending="Loading"
success={() => 'Success'}
error={() => 'Error'}
onError={onError}
/>,
)

unmount()

await act(async () => {
rejectPromise!(new Error('Failed'))
})

expect(onError).not.toHaveBeenCalled()
})

it('should not call onError if aborted due to dependency change', async () => {
let rejectFirstPromise: (reason?: unknown) => void
const firstPromise = new Promise((_, reject) => {
rejectFirstPromise = reject
})

const promiseFn = vi
.fn()
.mockReturnValueOnce(firstPromise)
.mockReturnValue(Promise.resolve())
const onError = vi.fn()

const { rerender } = render(
<AsyncBlock
promiseFn={promiseFn}
pending="Loading"
success={() => 'Success'}
error={() => 'Error'}
deps={[1]}
onError={onError}
/>,
)

rerender(
<AsyncBlock
promiseFn={promiseFn}
pending="Loading"
success={() => 'Success'}
error={() => 'Error'}
deps={[2]}
onError={onError}
/>,
)

await act(async () => {
rejectFirstPromise!(new Error('Aborted'))
})

expect(onError).not.toHaveBeenCalled()
})
})
42 changes: 31 additions & 11 deletions lib/components/AsyncBlock/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,40 @@ import {
* dependency-based re-execution, and manual reloads.
*
* @template T - The type of data returned by the async operation.
* @param props - Props to control the behavior and rendering of the async operation.
* @returns Rendered result based on async state.
* @param {AsyncBlockProps<T>} props - Props to control the behavior and rendering of the async operation.
* @returns {JSX.Element | null} Rendered result based on async state.
*
* @example
*
* ```tsx
* <AsyncBlock
* promiseFn={(signal) => fetch('/api/user', { signal }).then(res => res.json())}
* pending={<p>Loading...</p>}
* success={(data) => <UserProfile data={data} />}
* error={(err) => <p>Error: {err.message}</p>}
* timeOut={5000}
* deps={[userId]}
* />
* import { AsyncBlock } from '@galiprandi/react-tools';
*
* const UserProfileWrapper = ({ userId }) => (
* <AsyncBlock
* promiseFn={(signal) => fetch(`/api/user/${userId}`, { signal }).then(res => res.json())}
* pending={(reload) => (
* <div>
* <p>Loading user...</p>
* <button onClick={reload}>Cancel and Retry</button>
* </div>
* )}
* success={(user, reload) => (
* <div>
* <h1>{user.name}</h1>
* <button onClick={reload}>Refresh Data</button>
* </div>
* )}
* error={(err, reload) => (
* <div>
* <p>Error: {(err as Error).message}</p>
* <button onClick={reload}>Try Again</button>
* </div>
* )}
* timeOut={5000}
* deps={[userId]}
* onSuccess={(data) => console.log('Loaded:', data)}
* onError={(err) => console.error('Failed:', err)}
* />
* );
* ```
*/
export const AsyncBlock = <T,>({
Expand Down
Loading