How to handle offline case?
Hello, I'm implementing PWA and I need to handle case when user is offline and wants to load the page. If the page's data is not in react-query cache, I'd like to render different component and let user allow to subcribe to notification when page will be loaded (background-sync using SW). How to do this?
3 Replies
xenial-black•17mo ago
I could be wrong, but this sounds like it could be solved with Conditional Rendering. https://react.dev/learn/conditional-rendering
And the pattern is sometimes called a 'fallback'
Here is a crude approximation of what I do In my app:
return(
<>
{ data ? <PageContents/> : <FallbackPageContents/>}
</>
)
You could get more fancy with the data check, to also check if you're online or not. Depends on the needs of your app.
Conditional Rendering – React
The library for web and native user interfaces
variable-limeOP•17mo ago
The problem is that loader is trying to fetch data from the server, and if there's no internet connection I'd like to fetch data in the background. Right now, if app is offline, I get infinite loading state
like-gold•17mo ago
I assume you could disable the useQuery, based on the network state via
enabled
prop, and set initialData of the query, to the value inside the cache. The code would look something like this
Though default cache behavior is in-memory. You might find persistQueryClient more suitable for your needs.
https://tanstack.com/query/v4/docs/framework/react/plugins/persistQueryClient