-
In case of slow connection if user navigates off (unload) the page during the revalidation, browser aborts the fetch with an error and useSWR hook returns an error while page is still visible (after "beforeunload", but before "unload" event). In such a case the user may see an error message or error alert for a while when clicks on a link moving to another page (outside the SPA) causing frustration. The fix is to always returning stale data after "beforeunload" event is triggered instead of error. It could be implemented in the application logic itself, but isn't it the best to be handled by SWR? Here is an example code of the in app logic fix to depict better the problem: export default function Test() {
const [unloading, setUnloading] = useState(false);
const { data, error } = useSWR("/test");
useEffect(() => {
window.addEventListener("beforeunload", () => setUnloading(true));
}, []);
if (!unloading && error) {
console.error("ERROR!!!");
return <h1>ERROR!!!</h1>;
} else if (!data) {
return <h1>Loading ...</h1>;
} else {
return <h1>{data.message}</h1>;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
@hrabur I'm not sure what kind of fetcher you're using, but you might be able to handle the error thrown from fetcher due to browser navigation. if the error is caused by navigation, you can ignore it and let fetcher resolve. swr will use the error thrown from fetcher as returning error. |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot @huozhi . Inspired by you proposal to use
I've implemented a solution that uses the last data when errors appear after "beforeunload" event to update the cache. It works fine for my case. const useUnloadingAwareSwr = url => {
const [unloading, setUnloading] = useState(false);
const handleBeforeUnload = () => setUnloading(true);
useEffect(() => {
window.addEventListener("beforeunload", handleBeforeUnload);
}, []);
const result = useSWR(url);
if (unloading && result.data && result.error)
result.mutate(result.data, false);
return result;
}; Because navigating out on slow connection or slowly responding API, sounds like not very unusual case. Do you think it is good idea to make SWR itself handle this case. I imagine option like |
Beta Was this translation helpful? Give feedback.
@hrabur I'm not sure what kind of fetcher you're using, but you might be able to handle the error thrown from fetcher due to browser navigation. if the error is caused by navigation, you can ignore it and let fetcher resolve. swr will use the error thrown from fetcher as returning error.