-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
read cache during render #794
Conversation
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. Latest deployment of this branch, based on commit 2c02fa5:
|
This will possibly break the React hydration, we need to consider that. BTW, thanks for the sandboxes!! |
if we only sync the stateRef with cache when key changes, would it possibly break the React hydration ?
|
I don't know if we should do that (setting a ref's |
b836be6
to
d85c116
Compare
d85c116
to
a9c9af3
Compare
03f76c3
to
326315e
Compare
src/use-swr.ts
Outdated
const keys = Object.keys(payload) | ||
if ( | ||
keys.includes('data') && |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const keys = Object.keys(payload) | |
if ( | |
keys.includes('data') && | |
if ( | |
'data' in payload && |
Thank you so much for working on this! This is a pretty big change and lucky nothing breaks and the code is cleaner. |
Published as |
The problem
In swr, we have stateRef to store the data from the global cache.
So if the fetcher or the mutate function makes useSWR rerender, the stateRef is always sync with the cache.
But if useSWR rerender because of the sibling hooks rerender or the parent component rerender, it may return 'previous' data and stateRef is not sync with the cache
Related issues
Fixes #387: the parents rerender because of the mutate function, the child component will render twice, the first render will give a stale value and the second render which is scheduled by the mutate function.
Fixes #463: the sibling hooks rerender because of the fetcher, so other hook will return the 'stale' value.
Fixes #789: the parents rerender because of the timer. so the previous error is returned from the stateRef.
Repo
Possible solution
what if we do step 1 in every render ?During the render, we pass the current cache to the dispatch function.
swr/src/use-swr.ts
Lines 306 to 325 in 2248899