Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

344
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!