Reputation: 211
I have an application where a token get stored once the users open the app for the first time, and I need to check for that token when the app starts and create the navigator,
Approach 1
const getValue = async () => {
try {
value = await AsyncStorage.getItem('token').then((value) =>{
console.log(value)
})
} catch (error) {
console.log(error.message);
}
};
if (token != undefined) {
stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
} else {
stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}
In the first approach, it always renders the home screen even if the token is stored in the application
Second approach
const getValue = async () => {
try {
value = await AsyncStorage.getItem('token').then((value) =>{
if(value == null){
stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}else{
stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}
})
} catch (error) {
console.log(error.message);
}
};
This approach throws Cannot read property of router undefined
Is there a way to get this to work?
Navigation.js
export const getValue = async () => {
let VALUE;
try {
await AsyncStorage.getItem('token')
.then((value) =>{
if(value == null){
VALUE = stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}else{
VALUE = stackNavigator = createStackNavigator({
Products: Products,
Product: Product
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false
}
})
}
})
} catch (error) {
console.log(error.message);
}
return VALUE;
};
App.js
import { getValue } from './layout/navigation/Navigation';
let Navigation = createAppContainer(getValue());
class App extends React.Component {
render() {
return (<Navigation/>)
}
}
Upvotes: 1
Views: 360
Reputation: 2605
Create Routing
stackNavigator = createStackNavigator({
Home:Home,
Products: Products,
Product: Product,
Login : Login
},
{
headerMode: 'none',
initialRouteName : 'Home', // provide initial route : app will open with Home page
navigationOptions: {
headerVisible: false
},
})
// Export it with createAppContainer
export default createAppContainer(stackNavigator);
Import it to your App.js and use it as <Router/>
import Router from 'Application/navigation/routes';
Now what you can do is when user going to login then store their token to AsyncStorage and then redirect to home page.
In your home page you can add your token is exist or not code in mount lifecycle if you are not getting your token from storage then you can navigate your route to login screen.
Upvotes: 1