Denis2310
Denis2310

Reputation: 1218

How to parse a Promise from "await fetch()"?

I have a user detail page component. I would like to call fetchApiReponse() method and inside it there is a code for fetching external data from api with "await fetch()".

How to parse that response and return result to a component? I dont want to do this with getStaticProps() because I will fetch userId from url and add ti to api call url.

Here is my code:

export async function fetchApiResponse() {
  const sku = await useRouter().query.sku;
  const url = `https://jsonplaceholder.typicode.com/users?id=1`;
  console.log(url);

  const res = await fetch(url);
  const data = res.json();

  return data;
}

Component file:

export default function UserDetailPage(params) {
    const user = fetchApiUser();

    return (
        <>
            <h3>{user.name}</h3>
        </>
    );
}

Unfortunately that piece of code above is not working. It says that result from res.json() is a Promise

Upvotes: 1

Views: 2445

Answers (2)

Akidi
Akidi

Reputation: 935

Two things, one of them already mentioned in the comments by Yousaf:

const res = await fetch(url);
const data = await res.json(); 

You need to await res.json() since res.json() is a promise just like fetch. Awaiting is what you do to resolve the promise before moving on to the next block of code. ( At least that is how I understand it )

The other thing is in the first part of your code.

const sku = await useRouter().query.sku;

This should probably be

const sku = (await useRouter()).query.sku;

At least in my experience, I've had problems trying to access properties of an await Promise. It seems to me that it would attempt to access the properties of the function's return ( a Promise ) and not the value that I'm really trying to get at.

Of course that could be entirely me, my situation, and me not knowing what is really going on behind the scenes. So take it with a grain of salt on the last part.

Upvotes: 1

Denis2310
Denis2310

Reputation: 1218

How I resolved it:

I have moved my code from fetchApiResponse() function to getServerSideProps() and then I have passed json response to { props { .. } } and now I dont have to deal with Promises and parse a Promise and it works fine.

But yes I would still like to know how to parse a Promise result and how to deal with it.

Upvotes: 1

Related Questions