Skip to content
Open
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
2 changes: 1 addition & 1 deletion src/index/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ export const useSWRHandler = <Data = any, Error = any>(
// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (callbackSafeguard()) {
getConfig().onSuccess(newData, key, config)
getConfig().onSuccess?.(newData, key, config)
}
}
} catch (err: any) {
Expand Down
26 changes: 26 additions & 0 deletions test/use-swr-config-callbacks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,32 @@ describe('useSWR - config callbacks', () => {
expect(discardedEvents).toEqual([key])
})

it('should not cause infinite loading when onSuccess is undefined', async () => {
const key = createKey()
let fetchCount = 0
function Page() {
const { data, isLoading } = useSWR(
key,
() => {
fetchCount++
return createResponse('ok')
},
{
onSuccess: undefined
}
)
return <div>{isLoading ? 'loading' : `data: ${data}`}</div>
}

renderWithConfig(<Page />)
screen.getByText('loading')

await screen.findByText('data: ok')
// Wait a bit to ensure no extra retries are triggered.
await act(() => sleep(100))
expect(fetchCount).toBe(1)
})

it('should not trigger the onSuccess callback when discarded', async () => {
const key = createKey()
const discardedEvents = []
Expand Down