Skip to content

Commit 5fd537e

Browse files
authored
docs(react-native): add code examples for common use cases (TanStack#3042)
* docs: add React Native code examples for common use cases - Online status management - Refetch on App focus - Refresh on Screen focus * docs(react-native): use useOnlineManager example
1 parent aec640a commit 5fd537e

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

docs/src/pages/react-native.md

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,68 @@ id: react-native
33
title: React Native
44
---
55

6-
React Query is designed to work out of the box with React Native, with the exception of the devtools, which are only supported with React DOM at this time.
6+
React Query is designed to work out of the box with React Native, with the exception of the devtools, which are only supported with React DOM at this time.
77

88
There is a 3rd party [Flipper](https://fbflipper.com/docs/getting-started/react-native/) plugin which you can try: https://github.com/bgaleotti/react-query-native-devtools
99

1010
If you would like to help us make the built-in devtools platform agnostic, please let us know!
11+
12+
## Online status management
13+
14+
React Query already supports auto refetch on reconnect in web browser.
15+
To add this behavior in React Native you have to use React Query `onlineManager` as in the example below:
16+
17+
```ts
18+
import NetInfo from '@react-native-community/netinfo'
19+
import { onlineManager } from 'react-query'
20+
21+
onlineManager.setEventListener(setOnline => {
22+
return NetInfo.addEventListener(state => {
23+
setOnline(state.isConnected)
24+
})
25+
})
26+
```
27+
28+
## Refetch on App focus
29+
30+
In React Native you have to use React Query `focusManager` to refetch when the App is focused.
31+
You can use 'react-native-appstate-hook' to be notified when the App state has changed.
32+
33+
```ts
34+
import { focusManager } from 'react-query'
35+
import useAppState from 'react-native-appstate-hook'
36+
37+
function onAppStateChange(status: AppStateStatus) {
38+
if (Platform.OS !== 'web') {
39+
focusManager.setFocused(status === 'active')
40+
}
41+
}
42+
43+
useAppState({
44+
onChange: onAppStateChange,
45+
})
46+
```
47+
48+
## Refresh on Screen focus
49+
50+
In some situations, you may want to refetch the query when a React Native Screen is focused again.
51+
This custom hook will call the provided `refetch` function when the screen is focused again.
52+
53+
```ts
54+
import React from 'react'
55+
import { useFocusEffect } from '@react-navigation/native'
56+
57+
export function useRefreshOnFocus<T>(refetch: () => Promise<T>) {
58+
const enabledRef = React.useRef(false)
59+
60+
useFocusEffect(
61+
React.useCallback(() => {
62+
if (enabledRef.current) {
63+
refetch()
64+
} else {
65+
enabledRef.current = true
66+
}
67+
}, [refetch])
68+
)
69+
}
70+
```

0 commit comments

Comments
 (0)