Home > Net >  Making the login/logout function using AsyncStorage
Making the login/logout function using AsyncStorage

Time:08-26

I am making my first React Native app and I am in the process of making the login/logout functions of the app. I am trying to make the app remember the logged in user by using AsyncStorage. here's my code:

app.js-


import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Login from './components/login'
import Signup from './components/signup'
import Home from './components/home'
import Profile from './components/profile';
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, {useState, useEffect, useCallback, Component} from 'react'




const AppNavigator = createStackNavigator({
  Login: {screen: Login},
  Signup: {screen: Signup},
  Home: {screen: Home},
  Profile: {screen: Profile},
  
});

const AppNavigator2 = createStackNavigator({
  Home: {screen: Home},
  Login: {screen: Login},
  Signup: {screen: Signup},
  Profile: {screen: Profile},
  
});

const getData = async () => {
  try {
      const value = await AsyncStorage.getItem('@userauthkey')
      if (value !== null) {
          return value
      } else {
          return false
      }
  } catch (e) {
      console.log(e)
  }
}



const ch = async () => {
  const c = await getData();
  if (c) {
    
    console.log(c)
    return true 
  } else {
    return false
  }
};

const check = ch()
console.log(check)

const App = createAppContainer(  check ? AppNavigator2 : AppNavigator )




export default App;

When I run this the app automaticly goes to "AppNavigator2" regardless of whether the user is logged in or not. I checked the console and "check" does not show anything. How can I solve this issue?

CodePudding user response:

The content of the variable check is a Promise, which is a truthy value.

In order to have the boolean value you're expecting, you should wait for the async function ch to return the correct value.

You can achieve that by adding the keyword await when invoking the function ch.

const check = await ch();

  • Related