0

I'm currently trying to get axios running in a react hooks app. The basic get request is working fine and delivering the expected results, but here comes the problem:

I'm using 'zustand' for application state management and established a central backendService.js in which I have declared my async axios function 'getHome()'. The console.log(response.data); prints the expected data.

export const [useBackendStore, backendApi] = create((set, get) => ({
 env: environments.local, //is declared above
 home: null,


 getHome: async () => {
  return axios({ method: 'get', url: get().env + '/home/clean' })
  .then(response => {
    set({ home: response.data });
    console.log(response.data);
    return response.data;
  })
  .catch(error => {
    console.log(error);
  });

},

From another file I now want to call the getHome function and first of all log the results.

  const data = backendApi.getState().getHome();
  console.log(data);

And now the part I dont understand: The console.log gives me this

  Promise {<pending>}
  __proto__: Promise
  [[PromiseState]]: "fulfilled"
  [[PromiseResult]]: Object

The PromiseResult has the expected object but i cant figure out how to access it.

I'm pretty new to backend development so please forgive me if I made any obvious mistakes:) Thanks for your help!

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
dorndalf
  • 21
  • 3
  • your API call is asynchronous so that whenever you console it, it will be a promise with state pending. either you can use Async/Await mechanism or can use call back function .then(), .err() to get the response – Juhil Somaiya Feb 19 '21 at 12:24
  • 1
    @JuhilSomaiya this makes pretty much sense now... Thanks! – dorndalf Feb 19 '21 at 12:36
  • You might find this helpful about [promises and async](https://javascript.info/async). – 109149 Feb 19 '21 at 12:38

0 Answers0