Home > database >  Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'error')
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'error')

Time:09-29

const getToken = (userId, token) => {
  22 |   getmeToken(userId, token).then((info) => {
  23 |     console.log("INFO COMING", info);
> 24 |     if (info.error) {
  25 |      setInfo({ ...info, error: info.error });
  26 |     } else {
  27 |       const clientToken = info.clientToken;

What is meant by Unhandled rejection, cannot read properties of undefined??.

I have defined the error and also assigned a value for it, below is the code of useState

  const [info, setInfo] = useState({
    loading: false,
    success: false,
    clientToken: null,
    error:"",
    instance: {},
  });

As per the above code, I have defined and assigned the value for error, then why is the browser still showing cannot read properties of undefined. Can anyone please clarify this?

getmeToken function code is below

export const getmeToken = (userId, token) => {
    return fetch(` ${API}/payent/gettoken/${userId}`, {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`
        }
    }).then(response => {
        return response.json();
    })
    .catch(err => console.log(err))
}

CodePudding user response:

First, check the output of the getmeToken function. Then, you can use info?.error instead of info.error to handle this error.

Edit: Check the ${API}/payent/gettoken/${userId} url again. I think /payent/ is incorrect (/payment/ is correct)

  • Related