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

onlineManager.md

74 lines2.3 KB

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```