Skip to content

Commit

Permalink
fix: fix the issue that useSWR revalidation isn't triggered if the
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Ponyets committed Aug 5, 2023
1 parent d1b7169 commit f902daa
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion _internal/src/utils/mutate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ export async function internalMutate<Data>(
cache
) as GlobalState

const revalidators = EVENT_REVALIDATORS[key]
const startRevalidate = () => {
const revalidators = EVENT_REVALIDATORS[key]
if (revalidate) {
// Invalidate the key by deleting the concurrent request markers so new
// requests will not be deduped.
Expand Down
45 changes: 45 additions & 0 deletions test/use-swr-remote-mutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,51 @@ describe('useSWR - remote mutation', () => {
expect(logger).not.toHaveBeenCalledWith('bar')
})

it('should revalidate the SWR request that starts during the mutation', async () => {
const key = createKey()

function Page() {
const [triggered, setTriggered] = React.useState(false)
const { data } = useSWR(
triggered ? key : null,
async () => {
await sleep(10)
return 'foo'
},
{ revalidateOnMount: false }
)
const { trigger } = useSWRMutation(key, async () => {
await sleep(20)
return 'bar'
})

return (
<div>
<button
onClick={() => {
trigger(undefined)
setTriggered(true)
}}
>
trigger
</button>
<div>data:{data || 'none'}</div>
</div>
)
}

render(<Page />)

// mount
await screen.findByText('data:none')

fireEvent.click(screen.getByText('trigger'))
await act(() => sleep(50))

// The SWR request that starts during the mutation should be revalidated.
await screen.findByText('data:foo')
})

it('should revalidate after populating the cache', async () => {
const key = createKey()
const logger = jest.fn()
Expand Down

0 comments on commit f902daa

Please sign in to comment.