SWR is clearing the error data from cache on render even when the key is null, which should signal SWR not to try and fetch at all. When a user signs in to my app, I save their token to a cookie (and to react state) and the presence of the token tells SWR to perform a fetch. When this comes back with a server error, I need to display that error to the user and also clear their token from state and cookie. However, clearing the token triggers SWR to delete the cached error, so no error is displayed to the user.
If a render tells SWR not to fetch, don't delete old data/errors.
Here is a CodeSandbox. Try adding some text and clicking "Log In". You won't see any error message. If you comment out line 12 where I clear the token, you will see an error message.
SWR version ^0.3.2
@kristojorg when you call setToken in onError, the key is reset to undefined then the swr retrieve the error of key undefined. so that's why the error is not kept.
I see, the conditional fetching cannot be used to keep the old value around. Is there a suggested solution to this? Should I be saving the error to local state instead? This seems like it's working around the API of swr, but I don't really see a better solution. I don't actually think it would be wise for swr to return data for an old key when the key changes to null.
Thanks for your consideration here!
I'm having the same issue as @jarrodldavis, which is perhaps separate from @kristojorg's report because it seems to have started only in 0.3.3
It can also be seen / recreated in the docs for Error Handling:
https://swr.vercel.app/examples/error-handling
The docs example uses 0.3.1, and the error message stays visible while loading
Changing to 0.3.2, the error message is also visible while loading
Changing to 0.3.3, the error message now disappears when loading
I found these changes here: https://github.com/vercel/swr/pull/569/files#diff-755ef1ecc6f2f4c1cc601c6091dfcba5f674c653863b70913a115c0856a7b632R339-R343
when a hook is revalidating the state, it cleans the data / error of that key first (seems to make sense for me because we might want to clean up the states for last round revalidation).
IMO, if you'd like to preseve the error I think creating another hook to cache it in onError callback could achieve it, or use a useRef hook to compare with latest error returned from useSWR and update the ref when error changes and isn't nullable. this could be a short-term workaround.
we'll think of the more proper behavior of this case. thanks for reporting
hi all, bump this thread again. we reverted the behavior that let swr keep the error while revalidating. it's published in 0.3.6, plz upgrade to get this issue fixed. thanks