0

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);
    }
  };
Dominik
  • 6,078
  • 8
  • 37
  • 61
dylanb15
  • 25
  • 6

1 Answers1

1

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();
}, []);
LaatuJ
  • 26
  • 2