Skip to content

fix: isValidating cache inconsistence in mutatation #1411

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

Merged
merged 1 commit into from
Aug 30, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions src/use-swr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,13 @@ export const useSWRHandler = <Data = any, Error = any>(
return false
}

cache.set(keyErr, UNDEFINED)
cache.set(keyValidating, false)

const newState: State<Data, Error> = {
isValidating: false
}

// if there're other mutations(s), overlapped with the current revalidation:
// case 1:
// req------------------>res
Expand All @@ -223,17 +230,10 @@ export const useSWRHandler = <Data = any, Error = any>(
// case 3
MUTATION_END_TS[key] === 0)
) {
setState({ isValidating: false })
setState(newState)
return false
}

cache.set(keyErr, UNDEFINED)
cache.set(keyValidating, false)

const newState: State<Data, Error> = {
isValidating: false
}

if (!isUndefined(stateRef.current.error)) {
newState.error = UNDEFINED
}
Expand Down
46 changes: 46 additions & 0 deletions test/use-swr-local-mutation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -752,4 +752,50 @@ describe('useSWR - local mutation', () => {
await act(() => sleep(10))
expect(fetcher).toBeCalledTimes(2)
})

it('should reset isValidating after mutate', async () => {
const key = createKey()
function Data() {
const { data, isValidating } = useSWR(key, () =>
createResponse('data', { delay: 30 })
)
const { cache } = useSWRConfig()
const [, , , keyValidating] = serialize(key)
const cacheIsValidating = cache.get(keyValidating) || false
return (
<>
<p>data:{data}</p>
<p>isValidating:{isValidating.toString()}</p>
<p>cache:validating:{cacheIsValidating.toString()}</p>
</>
)
}

function Page() {
const { mutate: boundMutate } = useSWR(key, () =>
createResponse('data', { delay: 30 })
)
const [visible, setVisible] = useState(false)

return (
<div>
<button onClick={() => boundMutate(() => 'data', false)}>
preload
</button>
<button onClick={() => setVisible(true)}>show</button>
{visible && <Data />}
</div>
)
}
render(<Page />)

fireEvent.click(screen.getByText('preload'))
await act(() => sleep(20))
fireEvent.click(screen.getByText('show'))
screen.getByText('data:data')
screen.getByText('isValidating:true')
await act(() => sleep(20))
screen.getByText('data:data')
screen.getByText('isValidating:false')
})
})