'Trouble fetching token from localstorage - React

I'm new with react and i'm trying to create a basic login function using local storage and tokens.

I can see in my devtools that a token is actually stored but when i refresh the page, my application seems to have some trouble fetching it.

These are the two js-files in which i think the problem is located:


function Mypage () {
   
    const { token, setToken } = useToken();

     if(!token) {
        return <Login setToken={setToken} />
    }
 
  return (
      <>
    <h1>My page</h1>
    </>
  )
}

export default Mypage

export default function useToken() {
  
     const getToken = () => {
    const tokenString = localStorage.getItem('token');
    const userToken = JSON.parse(tokenString);
    return userToken?.token
  };    

   /*    const getToken = () => {
        const token = localStorage.getItem("token");
        return token !== null;
      };   */

  const [token, setToken] = useState();

  const saveToken = userToken => {
    localStorage.setItem('token', JSON.stringify(userToken));
    setToken(userToken.token);
  };

  return {
    setToken: saveToken,
    token
  }
}

I tried to mess around with two different const in which the commented out did work in "Mypage", but i would like it to be gathered in the same function "useToken".

Can anyone please give some input in where i might be messing up?



Solution 1:[1]

What I can see from your code is that there is a function to getToken which returns the token but you are not getting the token. In return, call the getToken function like you set saveToken.

return { 
   setToken: saveToken, 
   token: getToken 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Usama