Skip to content

Commit 714e497

Browse files
committed
Updates react native documentation for cache persistence based on AsyncStorage
1 parent c787a52 commit 714e497

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

pages/docs/advanced/react-native.en-US.mdx

+61
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,64 @@ import { AppState } from 'react-native'
9696
```
9797

9898
For `initReconnect`, it requires some 3rd party libraries such as [NetInfo](https://github.com/react-native-netinfo/react-native-netinfo) to subscribe to the network status. The implementation will be similar to the example above: receiving a `callback` function and trigger it when the network recovers from offline, so SWR can start a revalidation to keep your data up-to-date.
99+
100+
101+
### AsyncStorage Based Persistent Cache
102+
103+
You might want to sync your cache to `asyncStorage`. Here's an example implementation:
104+
105+
```jsx
106+
const useAsyncStorage = () => {
107+
const [cache, setCache] = useState(null)
108+
109+
useLayoutEffect(() => {
110+
// When initializing, we restore the data from `AsyncStorage` into a map.
111+
const getCache = async () => {
112+
const appCache = await AsyncStorage.getItem('app-cache') || '[]'
113+
// We still use the map for write & read for performance.
114+
setCache(new Map(JSON.parse(appCache)))
115+
}
116+
117+
getCache()
118+
}, [])
119+
120+
useLayoutEffect(() => {
121+
// Before closing the application, we write all the data to `localStorage`
122+
// and keep your cache up to date.
123+
const subscription = AppState.addEventListener('change', AsyncStorage => {
124+
if (nextAppState.match(/inactive|background/)) {
125+
const appCache = JSON.stringify(Array.from(cache.entries()))
126+
AsyncStorage.setItem('app-cache', appCache)
127+
}
128+
})
129+
130+
return () => {
131+
subscription.remove()
132+
}
133+
}, [cache])
134+
135+
return cache
136+
}
137+
138+
const App = () => {
139+
const cache = useAsyncStorage()
140+
141+
if (cache) {
142+
return (
143+
<SWRConfig
144+
value={{ provider: () => cache }}
145+
>
146+
<NavigationContainer>
147+
<HomeStack />
148+
</NavigationContainer>
149+
</SWRConfig>
150+
)
151+
}
152+
153+
return null
154+
}
155+
```
156+
157+
<Callout>
158+
Note that this example requires the cache provider to be a Map instance.
159+
</Callout>

0 commit comments

Comments
 (0)