0

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.

  • 1
    Does this answer your question? [Use Async/Await with Axios in React.js](https://stackoverflow.com/questions/46733354/use-async-await-with-axios-in-react-js) – Amila Senadheera Dec 02 '22 at 16:21
  • Note that the browsers' console.log is lazily evaluated (see https://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-exists-returns-undefined for more). – Heretic Monkey Dec 02 '22 at 16:30

1 Answers1

0

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!

geeky01adarsh
  • 312
  • 3
  • 14