-
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
data is always undefined first, even when cached #144
Comments
This is because SWR uses useEffect to read from cache I believe, I know when you enable Suspense it will try to read from cache right away. |
Amazing reproduction example! Thanks @herrstucki. The major reason is that when changing the key, it's still the same hook. For example: const [state] = useState(key) Only the initial However I do think this is fixable (https://github.com/zeit/swr/blob/master/src/use-swr.ts#L544-L547), by just trying to return the cached data (actually the Will let you know when this gets implemented 👍 |
Thanks @quietshu! I tried to figure out how things work by looking at the source but to be honest I didn't quite understand it at first glance 😅 I'm not quite sure why a changed key even needs to update state in the first place … reading from cache is synchronous anyway, no? Maybe a simplified pseudo-code example of what I mean: function useSWR(key, fetcher) {
const [isValidating, setValidating] = useState(false);
let currentData;
if (cache.has(key)) {
currentData = cache.get(key); // synchronous read
}
useEffect(() => {
if (needsRevalidating(key)) {
// will update cache, cache will notify "subscribers" via context or whatever
triggerRevalidating(key)
setValidating(true)
}
}, [key, setValidating])
return { data: currentData, isValidating };
} |
* fix the case that the arg array is empty * fix hash primitive types * add prefetch to the readme * improve wording * return cached state and remove hydration, fixes #144 * remove useHydration
Whenever a key is used that has already cached data,
data
will beundefined
anyway first and then immediately cause a re-render with the cached data.I've set up an example here:
https://codesandbox.io/s/determined-almeida-3nwpv
You'll see that even for cached results, the sequence will be like this:
… where I would expect a sequence like this:
The text was updated successfully, but these errors were encountered: