diff --git a/pages/docs/advanced/react-native.en-US.mdx b/pages/docs/advanced/react-native.en-US.mdx index 6c1e246a6..efdf9fd7d 100644 --- a/pages/docs/advanced/react-native.en-US.mdx +++ b/pages/docs/advanced/react-native.en-US.mdx @@ -9,7 +9,6 @@ import Callout from 'nextra-theme-docs/callout' Unlike React running inside the browsers, React Native has a very different user experience. For example there is no “tab focus”, switching from the background to the app is considered as a “focus” instead. To customize these behaviors, you can replace the default browser `focus` and `online` events listeners with React Native’s app state detection and other native ported API, and configure SWR to use them. - ## Example @@ -96,3 +95,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. + + + + Note that this example requires the cache provider to be a Map instance. + + +### 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', currentState => { + if (currentState === 'inactive' || currentState === '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 +} +```