Skip to content

Commit 0505d07

Browse files
authored
Fix the issue that useSWR revalidation isn't triggered if the useSWR call happens after mutation (#2731)
fix: fix the issue that useSWR revalidation isn't triggered if the useSWR call happens after mutation. E.g.: req------------->res mutate------->end In this case, the res would be ignored while req would not be triggered a revalidation.
1 parent d1b7169 commit 0505d07

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

_internal/src/utils/mutate.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,8 @@ export async function internalMutate<Data>(
9797
cache
9898
) as GlobalState
9999

100-
const revalidators = EVENT_REVALIDATORS[key]
101100
const startRevalidate = () => {
101+
const revalidators = EVENT_REVALIDATORS[key]
102102
if (revalidate) {
103103
// Invalidate the key by deleting the concurrent request markers so new
104104
// requests will not be deduped.

test/use-swr-remote-mutation.test.tsx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,51 @@ describe('useSWR - remote mutation', () => {
537537
expect(logger).not.toHaveBeenCalledWith('bar')
538538
})
539539

540+
it('should revalidate the SWR request that starts during the mutation', async () => {
541+
const key = createKey()
542+
543+
function Page() {
544+
const [triggered, setTriggered] = React.useState(false)
545+
const { data } = useSWR(
546+
triggered ? key : null,
547+
async () => {
548+
await sleep(10)
549+
return 'foo'
550+
},
551+
{ revalidateOnMount: false }
552+
)
553+
const { trigger } = useSWRMutation(key, async () => {
554+
await sleep(20)
555+
return 'bar'
556+
})
557+
558+
return (
559+
<div>
560+
<button
561+
onClick={() => {
562+
trigger(undefined)
563+
setTriggered(true)
564+
}}
565+
>
566+
trigger
567+
</button>
568+
<div>data:{data || 'none'}</div>
569+
</div>
570+
)
571+
}
572+
573+
render(<Page />)
574+
575+
// mount
576+
await screen.findByText('data:none')
577+
578+
fireEvent.click(screen.getByText('trigger'))
579+
await act(() => sleep(50))
580+
581+
// The SWR request that starts during the mutation should be revalidated.
582+
await screen.findByText('data:foo')
583+
})
584+
540585
it('should revalidate after populating the cache', async () => {
541586
const key = createKey()
542587
const logger = jest.fn()

0 commit comments

Comments
 (0)