The OnlineManager
manages the online state within TanStack Query. It can be used to change the default event listeners or to manually change the online state.
Per default, the
onlineManager
assumes an active network connection, and listens to theonline
andoffline
events on thewindow
object to detect changes.
In previous versions,
navigator.onLine
was used to determine the network status. However, it doesn't work well in Chromium based browsers. There are a lot of issues around false negatives, which lead to Queries being wrongfully marked asoffline
.
To circumvent this, we now always start with
online: true
and only listen toonline
andoffline
events to update the status.
This should reduce the likelihood of false negatives, however, it might mean false positives for offline apps that load via serviceWorkers, which can work even without an internet connection.
Its available methods are:
onlineManager.setEventListener
#
setEventListener
can be used to set a custom event listener:
1import NetInfo from '@react-native-community/netinfo'
2import { onlineManager } from '@tanstack/react-query'
3
4onlineManager.setEventListener((setOnline) => {
5 return NetInfo.addEventListener((state) => {
6 setOnline(!!state.isConnected)
7 })
8})
onlineManager.subscribe
#
subscribe
can be used to subscribe to changes in the online state. It returns an unsubscribe function:
1import { onlineManager } from '@tanstack/react-query'
2
3const unsubscribe = onlineManager.subscribe((isOnline) => {
4 console.log('isOnline', isOnline)
5})
onlineManager.setOnline
#
setOnline
can be used to manually set the online state.
1import { onlineManager } from '@tanstack/react-query'
2
3// Set to online
4onlineManager.setOnline(true)
5
6// Set to offline
7onlineManager.setOnline(false)
Options
online: boolean
onlineManager.isOnline
#
isOnline
can be used to get the current online state.
1const isOnline = onlineManager.isOnline()