-1

I have the following code in a react-redux powered application. The code is split across a couple of files but I've just combined it below for simplicity:

const token = localStorage.getItem('token');

const authClient = axios.create({
    baseURL: "http://api.empaygo.local",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    }
});

const getUser = async (userId) => {
    const result = await authClient.get(`/users/${userId}`);
    return result;
}


const user = users.getUser(1);
console.log(user);

The final console log is always:

Promise result

And I cannot work out how to get the data that I need out of it. Any help would great :)

Wildcard27
  • 1,437
  • 18
  • 48
  • also: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Quentin Feb 01 '21 at 09:46
  • @Quentin This did help, thank you. I understand that I should probably use a callback, but I need to stop my component from rendering (or show that it is loading) before I get the response back. I could have just spent too long looking at this to work it out but are you able to help at all? – Wildcard27 Feb 01 '21 at 11:35
  • You can't do that. Have the async function store a value in the state which will trigger a rerender. – Quentin Feb 01 '21 at 11:37

1 Answers1

0

try this:

const user = users.getUser(1);
// inside this cb you will get actual object
user.then((data) => console.log(data))

or just

 users.getUser(1).then((data) => {
   // you can set this data into state or return another Promise
   console.log(data)
 })

You have to work with Promise

  • But I'm trying to assign the response data to a variable to use throughout the component, not just console log it – Wildcard27 Feb 01 '21 at 09:55
  • Inside callback function, you can do whatever you want. Assign to a variable if needed or save is state ..... – user3753974 Feb 01 '21 at 09:58