Home > Enterprise >  Issue with Axios / React return undefined
Issue with Axios / React return undefined

Time:12-03

I have an issue with React when I try to retrieve the value of return.

The code:

export const RuoloOnline = (jwt) => {
    axios.get("http://localhost:1337/api/users/me",
        {
            headers: {
                "Authorization": `Bearer ${jwt}`
            }
        }
    ).then((res) => { return (res.data.ruolo) }).catch(() => {return 0}) 

if I put a console.log the value is correctly viewed. If I try to call this function outside the file, it generates an undefined return.

CodePudding user response:

The issue you're experiencing is likely because you're not returning the value correctly from the RuoloOnline function. In JavaScript, return statements immediately exit the function they are in, so the code after the return statement will never be executed.

Here's one way you could fix your code:

export const RuoloOnline = (jwt) => {
  return axios.get("http://localhost:1337/api/users/me",
    {
      headers: {
        "Authorization": `Bearer ${jwt}`
      }
    }
  ).then((res) => res.data.ruolo).catch(() => 0);
}

In this version of the code, we're returning the result of the axios.get call directly, so the value will be returned correctly when the function is called.

CodePudding user response:

Try using asynchronous function calls instead of this function. Your modified code will be

export const RuoloOnline = async (jwt) ={
    return await axios.get("http://localhost:1337/api/users/me",
       {
           headers: { 
                "Authorization": `Bearer ${jwt}`
            }
        }
   );
}

Hope it helps!

  • Related