dylanb15
dylanb15

Reputation: 21

async storage is not working when I reload the react-native app

I get to the point where after I log in I go to my Home and Profile screens, but if I reload or close the app and then open it again instead of open it on the Home screen, it goes to the login again. I tried with AsyncStorage to save the user until I log out and then remove it but still not working. Any helps?

APP.JS

const getToken = async () => {
    let value = await AsyncStorage.getItem('token');
    if (value !== null) {
      setToken(value);
    }
  };

  useEffect(() => {
    getToken();
  }, []);

  return (
    <NavigationContainer>
      <stateContext.Provider value={{token, setToken}}>
         <Stack.Navigator screenOptions={{headerShown: false}}>
         {!token ? (
            <>
            <Stack.Screen name="Login" component={LoginPage} />
            <Stack.Screen name="Verification" component={VerificationPage} />
            </>
         ) : (
            <>
            <Stack.Screen name="Home" component={Home}/>
            <Stack.Screen name="Profile" component={Profile} />
            </> )}
         </Stack.Navigator>
       </stateContext.Provider>
      </NavigationContainer>  
     )

LOGIN.JS

  const phoneNumberLogin = async (phoneNumber) => {
    try {
      let res = await axios({
        url: `XXXX`,
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      if (res.status == 200) {
        setToken(res.data.firstName);
        AsyncStorage.setItem('token', token);
      }
      return res.data;
    } catch (err) {
      console.error(err);
    }
  };

Upvotes: 0

Views: 1456

Answers (1)

LaatuJ
LaatuJ

Reputation: 26

Try to move getToken function inside useEffect. I have had problems with async functions and useEffect and this solution have worked for me.

useEffect(() => {
   const getToken = async () => {
      let value = await AsyncStorage.getItem('token');
      if (value !== null) {
         setToken(value);
      }
   };
getToken();
}, []);

Upvotes: 1

Related Questions