Skip to content
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

Prevent polling when browser is offline #203

Merged
merged 6 commits into from
Dec 18, 2019

Conversation

daneden
Copy link
Contributor

@daneden daneden commented Dec 16, 2019

I love useSwr! I’m using it to build a London Underground status site.

While testing the app on slow/no network speeds, I noticed that useSwr will continue polling endpoints even if the navigator is offline. This PR adds an additional boolean check in the tick function to ensure that requests aren’t sent if the browser is offline.

@sergiodxa
Copy link
Contributor

Maybe it will be great to detect when the user is back online to trigger a revalidation.

@daneden
Copy link
Contributor Author

daneden commented Dec 16, 2019

I’m confused about why, but I’m getting an “Invalid hook call” error (as in Rules of Hooks) when I test this locally. I’m not sure if it’s an issue with different React modules being loaded; I’m also struggling to get tests to run locally, but it looks like tests pass in Travis!

Let me know if you also run into problems.


Update: turns out the hook warning was indeed because of extraneous dependencies: this fix seems to work as intended after all 😊

@shuding
Copy link
Member

shuding commented Dec 17, 2019

Thanks a lot! Could you also create an option for it (same as config.refreshWhenHidden)? Because sometimes people use SWR for local states too so it can work in offline.

@daneden
Copy link
Contributor Author

daneden commented Dec 17, 2019

@quietshu no problem! Added as a config option. I also took @sergiodxa’s suggestion and added an additional revalidateOnReconnect option that will add an event listener to the online event and trigger a fetch.

@rauchg
Copy link
Member

rauchg commented Dec 18, 2019

It just dawned on me we didn't have this capability. That's epic @daneden

src/use-swr.ts Outdated Show resolved Hide resolved
@daneden daneden requested a review from shuding December 18, 2019 19:56
@shuding
Copy link
Member

shuding commented Dec 18, 2019

Thank you @daneden !

@shuding shuding merged commit 0cc1a56 into vercel:master Dec 18, 2019
@shuding
Copy link
Member

shuding commented Dec 18, 2019

Published in swr@0.1.15 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants