Aman Sharma
Aman Sharma

Reputation: 63

Not able to store logged In user data, using AsyncStorage API

I am new to react native so please bear with me.

Here is my access token's async storage, the token is one of the parameters as the response from API. and this code is in Login Screen

async getToken() {

 try{
 const token = await AsyncStorage.getItem('ACCESS_TOKEN');
 if(token !== null) {
   this.props.navigation.navigate('Profile')
 }
 else{
   this.props.navigation.navigate('Login')
 }
 }
  catch (error){
  console.log('Something went wrong');
 }
 }

 async storeToken(accessToken) {

  try{
   await AsyncStorage.setItem('ACCESS_TOKEN', accessToken);
       this.getToken();
   }
    catch (error) {
     console.log('something went wrong');
   }

   }

when I log-in, it is navigating me to Profile page but after refreshing the app it is going back to the login page or my navigation tree

Here is my app.js where navigation is set

const TodoNav = StackNavigator({

 Login: { screen: Login },
 SignUp: { screen: SignUp },
 ForgotPassword: { screen: ForgotPassword },
 Profile: { screen: Profile },
 MenuScreen: { screen: MenuScreen },
  }, {
      mode: 'modal'
  })

 export default class App extends Component{

  render() {
   return (
     <TodoNav />
      );
    }
   }

Upvotes: 1

Views: 379

Answers (1)

Aseem Sharma
Aseem Sharma

Reputation: 1853

AsyncStorage is not responsible to save the navigation state of your application, it will store the data as you pass to it. Refer the documentation of AsyncStorage for more details(Here) In order to show Home screen, you need to check your async storage data at App.js Then create Navigation stack accordingly, for eg:

If you find AccessToken:

 const TodoNavAuthenticated = StackNavigator({

 Profile: { screen: Profile },
 MenuScreen: { screen: MenuScreen },
  }, {
      mode: 'modal'
  })

If Accesstoken is not found means you are not logged in so:

const TodoNav = StackNavigator({

 Login: { screen: Login },
 SignUp: { screen: SignUp },
 ForgotPassword: { screen: ForgotPassword },
 Profile: { screen: Profile },
 MenuScreen: { screen: MenuScreen },
  }, {
      mode: 'modal'
  })

This needs to be checked when your using <ToDoNav /> i.e. inside your App.js render() method.

Upvotes: 1

Related Questions