Open History to see the last commit
1---
2id: OnlineManager
3title: OnlineManager
4---
5β
6The `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.
7β
8> Per default, the `onlineManager` assumes an active network connection, and listens to the `online` and `offline` events on the `window` object to detect changes.
9β
10> 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](https://bugs.chromium.org/p/chromium/issues/list?q=navigator.online) around false negatives, which lead to Queries being wrongfully marked as `offline`.
11β
12> To circumvent this, we now always start with `online: true` and only listen to `online` and `offline` events to update the status.
13β
14> 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.
15β
16Its available methods are:
17β
18- [`setEventListener`](#onlinemanagerseteventlistener)
19- [`subscribe`](#onlinemanagersubscribe)
20- [`setOnline`](#onlinemanagersetonline)
21- [`isOnline`](#onlinemanagerisonline)
22β
23## `onlineManager.setEventListener`
24β
25`setEventListener` can be used to set a custom event listener:
26β
27```tsx
28import NetInfo from '@react-native-community/netinfo'
29import { onlineManager } from '@tanstack/react-query'
30β
31onlineManager.setEventListener((setOnline) => {
32 return NetInfo.addEventListener((state) => {
33 setOnline(!!state.isConnected)
34 })
35})
36```
37β
38## `onlineManager.subscribe`
39β
40`subscribe` can be used to subscribe to changes in the online state. It returns an unsubscribe function:
41β
42```tsx
43import { onlineManager } from '@tanstack/react-query'
44β
45const unsubscribe = onlineManager.subscribe((isOnline) => {
46 console.log('isOnline', isOnline)
47})
48```
49β
50## `onlineManager.setOnline`
51β
52`setOnline` can be used to manually set the online state.
53β
54```tsx
55import { onlineManager } from '@tanstack/react-query'
56β
57// Set to online
58onlineManager.setOnline(true)
59β
60// Set to offline
61onlineManager.setOnline(false)
62```
63β
64**Options**
65β
66- `online: boolean`
67β
68## `onlineManager.isOnline`
69β
70`isOnline` can be used to get the current online state.
71β
72```tsx
73const isOnline = onlineManager.isOnline()
74```