T
TanStack17mo ago
variable-lime

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
xenial-black17mo 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-lime
variable-limeOP17mo 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
like-gold17mo 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
const networkState:boolean = isConnected && isInternetReachable
const queryClient = useQueryClient()
const {data} = useQuery({queryKey, queryFn, enabled:networkState, initialData:queryClient.getQueryData(queryKey)})
const networkState:boolean = isConnected && isInternetReachable
const queryClient = useQueryClient()
const {data} = useQuery({queryKey, queryFn, enabled:networkState, initialData:queryClient.getQueryData(queryKey)})
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

Did you find this page helpful?