Skip to content

Commit

Permalink
fix: isValidating cache inconsistence in mutatation (#1411)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi authored Aug 30, 2021
1 parent 9d99864 commit b819c25
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
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')
})
})

0 comments on commit b819c25

Please sign in to comment.