I am using React navigation v6 for my react native application. I am stuck at trying to detect if the app is launched for the first time by the user or not.
I have tried to set FIRST_LAUNCH
through AsyncStorage and then depending on its value I set the initialRouteName
in the Stack.Navigator
. This doesn’t seem to work as I came to know that createNativeStackNavigator
is synchronous doesn’t wait for the getItem
‘s promise to be fulfilled or rejected to finish up being executed.
App.js
const App = () => {
useEffect(() => {
SplashScreen.hide();
},[]);
return (
<View style={styles.container}>
<Routes />
</View>
);
};
Routes.js
const Stack = createNativeStackNavigator();
function Routes(){
const [firstLaunch , setFirstLaunch] = useState(true);
const checkFirstLaunch = () => {
AsyncStorage.getItem('FIRST_LAUNCH').then(value => {
if(value === null){
AsyncStorage.setItem('FIRST_LAUNCH', 'false');
}
setFirstLaunch(false);
})
}
useEffect(() => {
checkFirstLaunch();
}, [])
return(
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}
initialRouteName={firstLaunch ? 'Onboarding' : 'TenantHome'}
>
<Stack.Screen name="Onboarding" component={OnboardingRoutes} />
<Stack.Screen name="TenantHome" component={TenantRoutes} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default Routes;
This doesn’t seem to work and firstLaunch
is always true.
I have also read a solution where someone suggested to make a splash screen of my own which is the default first screen and use that to navigate to the onboarding or tenant home screen accordingly. But I already have a splash screen set up by LaunchScreen.xib
and hiding it using SplashScreen.hide()
in App.js. Also I don’t know if manually creating it is good practice or not.
Can someone help me get about this?
2
Answers
Maybe you should try async/await like this:
Or:
And async storage work not like
localStorage
. that’s why sometimes a little bit we get confused. We get different data fromasyncstorage
If you want to use
AsyncStorage
, then the below code should work fine:If the above code still does not work, then you can try using
react-native-sqlite-storage
. I know it will increase the complexity of the code but it is much faster than theAsyncStorage
, so it will also improve the performance of your app.Check the below code for your reference: