Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Only trigger the success event if not discarded #1529

Merged
merged 2 commits into from
Oct 4, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,11 +194,6 @@ export const useSWRHandler = <Data = any, Error = any>(
// If the request isn't interrupted, clean it up after the
// deduplication interval.
setTimeout(() => cleanupState(startAt), config.dedupingInterval)

// Trigger the successful callback.
if (isCallbackSafe()) {
getConfig().onSuccess(newData, key, config)
}
}

// If there're other ongoing request(s), started after the current one,
Expand Down Expand Up @@ -257,6 +252,13 @@ export const useSWRHandler = <Data = any, Error = any>(
if (!compare(cache.get(key), newData)) {
cache.set(key, newData)
}

// Trigger the successful callback if it's the original request.
if (shouldStartNewRequest) {
if (isCallbackSafe()) {
getConfig().onSuccess(newData, key, config)
}
}
} catch (err) {
// @ts-ignore
cleanupState(startAt)
Expand Down
33 changes: 33 additions & 0 deletions test/use-swr-config-callbacks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,37 @@ describe('useSWR - config callbacks', () => {
// Should have one event recorded.
expect(discardedEvents).toEqual([key])
})

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

function Page() {
const { mutate } = useSWR(
key,
() => createResponse('foo', { delay: 50 }),
{
onDiscarded: k => {
discardedEvents.push(k)
},
onSuccess: d => {
successEvents.push(d)
}
}
)
return <div onClick={() => mutate('bar', false)}>mutate</div>
}

renderWithConfig(<Page />)

screen.getByText('mutate')
await act(() => sleep(10))
fireEvent.click(screen.getByText('mutate'))
await act(() => sleep(80))

// Should have one event recorded.
expect(discardedEvents).toEqual([key])
expect(successEvents).toEqual([])
})
})