Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

onlineManager.md

76 lines2.3 KB

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