Created
July 18, 2021 10:30
-
-
Save YajanaRao/e2abd49192748d4eb806e646cdfef83c to your computer and use it in GitHub Desktop.
Persist navigation state in react navigation 5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { Linking, Platform, ActivityIndicator } from 'react-native'; | |
import AsyncStorage from '@react-native-async-storage/async-storage'; | |
import { NavigationContainer } from '@react-navigation/native'; | |
const PERSISTENCE_KEY = 'NAVIGATION_STATE'; | |
import { AppNavigation } from './navigation/AppNavigation'; | |
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 <ActivityIndicator/>; | |
} | |
return ( | |
<NavigationContainer | |
initialState={initialState} | |
onStateChange={(state) => | |
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state)) | |
}> | |
<AppNavigation/> | |
</NavigationContainer> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment