Error cleared on next render
See original GitHub issueBug report
Description / Observed Behavior
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.
Expected Behavior
If a render tells SWR not to fetch, don’t delete old data/errors.
Repro Steps / Code Example
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.
Additional Context
SWR version ^0.3.2
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (3 by maintainers)
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
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 auseRef
hook to compare with latest error returned fromuseSWR
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