OnlineManager
Source URL: https://tanstack.com/query/latest/docs/reference/onlineManager
OnlineManager
Section titled “OnlineManager”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
onlineManagerassumes an active network connection, and listens to theonlineandofflineevents on thewindowobject to detect changes.
In previous versions,
navigator.onLinewas 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: trueand only listen toonlineandofflineevents 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
Section titled “onlineManager.setEventListener”setEventListener can be used to set a custom event listener:
import NetInfo from '@react-native-community/netinfo'import { onlineManager } from '@tanstack/react-query'
onlineManager.setEventListener((setOnline) => { return NetInfo.addEventListener((state) => { setOnline(!!state.isConnected) })})onlineManager.subscribe
Section titled “onlineManager.subscribe”subscribe can be used to subscribe to changes in the online state. It returns an unsubscribe function:
import { onlineManager } from '@tanstack/react-query'
const unsubscribe = onlineManager.subscribe((isOnline) => { console.log('isOnline', isOnline)})onlineManager.setOnline
Section titled “onlineManager.setOnline”setOnline can be used to manually set the online state.
import { onlineManager } from '@tanstack/react-query'
// Set to onlineonlineManager.setOnline(true)
// Set to offlineonlineManager.setOnline(false)Options
online: boolean
onlineManager.isOnline
Section titled “onlineManager.isOnline”isOnline can be used to get the current online state.
const isOnline = onlineManager.isOnline()