From fe14c0f2da5991847e38270b042b18a382119b4e Mon Sep 17 00:00:00 2001 From: Jesus Hernandez Date: Tue, 8 Mar 2022 14:05:12 -0500 Subject: [PATCH] Updates react native documentation for cache persistence based on AsyncStorage --- pages/docs/advanced/react-native.en-US.mdx | 61 ++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/pages/docs/advanced/react-native.en-US.mdx b/pages/docs/advanced/react-native.en-US.mdx index 6c1e246a6..30a07c19d 100644 --- a/pages/docs/advanced/react-native.en-US.mdx +++ b/pages/docs/advanced/react-native.en-US.mdx @@ -96,3 +96,64 @@ import { AppState } from 'react-native' ``` 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. + + +### AsyncStorage Based Persistent Cache + +You might want to sync your cache to `asyncStorage`. Here's an example implementation: + +```jsx +const useAsyncStorage = () => { + const [cache, setCache] = useState(null) + + useLayoutEffect(() => { + // When initializing, we restore the data from `AsyncStorage` into a map. + const getCache = async () => { + const appCache = await AsyncStorage.getItem('app-cache') || '[]' + // We still use the map for write & read for performance. + setStore(new Map(JSON.parse(appCache))) + } + + getCache() + }, []) + + useLayoutEffect(() => { + // Before closing the application, we write all the data to `localStorage` + // and keep your cache up to date. + const subscription = AppState.addEventListener('change', nextAppState => { + if (nextAppState.match(/inactive|background/)) { + const appCache = JSON.stringify(Array.from(cache.entries())) + AsyncStorage.setItem('app-cache', appCache) + } + }) + + return () => { + subscription.remove() + } + }, [cache]) + + return cache +} + +const App = () => { + const store = useAsyncStorage() + + if (store) { + return ( + store }} + > + + + + + ) + } + + return null +} +``` + + + Note that this example requires the cache provider to be a Map instance. +