#Promise doesn't resolve in an Await Tag

17 messages · Page 1 of 1 (latest)

dull glen
#

Hi! I'm trying to fetch data inside an Await tag in React, but the promise doesn't resolve and thus I can't get my data. Any ideas? Here're some useful screen shots: and my get function from the api is :

export async function getHostBooks(){

const res = await fetch("/api/host/Books");

if (!res.ok){
    throw {
        message:'Failed to fetch host books',
        statusText:res.statusText,
        status: res.status
    }
}
const data = await res.json();

return data.books;

}

My fake mirage server end point is :

this.get('/host/Books', () => {
//console.log('we are in the second get.')
return books.filter(x=>x.hostId==='123')
})

But I'm pretty sure I get the right response from the fake server.. Thanks for your help!

junior forge
#

Don't you have to use state in a react fetch?

viscid aspen
#

Check the console and network tab in dev tools, that might give you an idea of what is going on.

dull glen
swift bramble
#

Would you be able to share a scrim, gh repo or codesandbox with us?

#

I cannot spot any issue with the code unless the generateBooks doesn't do something properly. It would be useful if we could play with your code a bit.

dull glen
#

The branch is the createBooksPage, I'm not focusing on the style so it's pretty ugly, but it does do the functionalities I wanted 🙂

swift bramble
#

@dull glen , the problem was with your loader:

export const loader = () => {
  const data = getHostBooks();
  return defer({ dataPromise: data });
};

As you can see your loader is not declared as async hence the data as you correctly state is a Promise, so dataPromise will be a Promise itself.

The simple solution is to define loader as an async function and await for the data:

export const loader = async () => {
  const data = await getHostBooks();
  return defer({ dataPromise: data });
};
dull glen
#

Hi @swift bramble Thanks for your help! but I still can't get the data, it's saying now: An error occured.Cannot read properties of undefined (reading 'map') In the generateBooks function..

swift bramble
#

double check your mirage server and what it returns. The data could probably be undefined

swift bramble
#

@dull glen , the problem is with your server.
you are returning the following: data.books

#

while data itself is the array of the filtered books

#

all you have to do is return data and you will see your books

dull glen
#

Oh Yeah! You're right! I did mix up things a little, Thanks a lot for your help @swift bramble