Skip to content
New issue

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

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

Already on GitHub? # to your account

Fix the issue that useSWR revalidation isn't triggered if the useSWR call happens after mutation #2731

Merged
merged 1 commit into from
Aug 11, 2023
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
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