Search code examples
reactjsauthenticationtiming

React auth with localStorage


The below code work for logging in but I keep getting an error of undefined at first, I believe it might be the timing of everything, the local storage setItem takes too long, trying to set a delay but am not managing.

    async function login(username, password) {
         const response = await axios.post(API_URL + "signin", {
            username,
            password
          });
    
          if (response.data.accessToken && typeof window !== 'undefined') {
            localStorage.setItem("user", JSON.stringify(response.data));
         }
          
        return response.data;
 }

Solution

  • problem was where I was loading username was the local storage wasnt set yet ,so the system responded with undefined ,to fix the proble just set an if statement saying toad the usersDetails when available