State persistence
References: State persistence
App.tsx
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as React from 'react';
import {Linking, Platform} from 'react-native';
import RouterRoot from 'react-native-auto-route';
const PERSISTENCE_KEY = 'NAVIGATION_STATE_V1';
export default function App() {
const [isReady, setIsReady] = React.useState(false);
const [initialState, setInitialState] = React.useState();
React.useEffect(() => {
const restoreState = async () => {
try {
const initialUrl = await Linking.getInitialURL();
if (Platform.OS !== 'web' && initialUrl == null) {
// Only restore state if there's no deep link and we're not on web
const savedStateString = await AsyncStorage.getItem(PERSISTENCE_KEY);
const state = savedStateString
? JSON.parse(savedStateString)
: undefined;
if (state !== undefined) {
setInitialState(state);
}
}
} finally {
setIsReady(true);
}
};
if (!isReady) {
restoreState();
}
}, [isReady]);
if (!isReady) {
return null;
}
return (
<RouterRoot
initialState={initialState}
onStateChange={(_, navState) =>
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(navState))
}
/>
);
}