0

I can log in user if it enters correct password but when I enter wrong password it shows me "access_token" is undefined.

This is my useToken.js file

import { useState } from "react";

export default function useToken() {

  const getToken = () => {
    const tokenString = sessionStorage.getItem("access_token");
    const userToken = JSON.parse(tokenString);
    return userToken?.access_token;
  };

  const [token, setToken] = useState(getToken());

  const saveToken = userToken => {
    sessionStorage.setItem('access_token', JSON.stringify(userToken.data));
    setToken(userToken.data.access_token);
  };

  return {
    setToken: saveToken,
    token
  }

}

This is inside my Login.js file where I handle this submit

    const handleSubmit = async e => {
        e.preventDefault();
        const token = await loginUser({
          email,
          password
        });
        setToken(token);
      }

And finally in my App.js file I show login page by:

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

How can I check for undefined if they enter wrong password or username redirect to login page.

incredible123
  • 103
  • 11

2 Answers2

0

First, have a look at this answer. Once managed to write a logic for isUndefined, embed it with a ternary operator like:

{ isUndefined ?
    // do these if true
    :
    // do these if false
}
Manny
  • 679
  • 5
  • 12
  • I've given that a go before but there is something else wrong here aside from checking for undefined since it still is showing me undefined. – incredible123 Jul 26 '21 at 04:49
0

The error is "cannot read access_token of undefined", which means userToken.data is undefined. This is most likely because the password is wrong. use the following.

userToken?.data?.access_token
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45