简体   繁体   中英

How do I pass two (or more) API props to a NextJs Page?

I'm trying to render a page with two props from different API fetches.

The adress bar looks like this: http://localhost:3000/startpage?id=1

And the code looks like this, with the first API fetch:

import { useRouter } from "next/router";

export const getServerSideProps = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();
  // console.log(data);

  return {
    props: { user: data },
  };
};

Second API fetch looks like this

export const getServerSideProps2 = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}/favorites`);
  const data = await res.json();
  //console.log(data);

  return {
    props: { favorites: data },
  };
};

And the page that I am trying to render then looks like this:

function StartPage( {user, favorites} ){
  return (
    <div>
      <div className={styles.formGroup}>
        <h1>Welcome {user.name}</h1>
      </div>
      <div>
        <h1>These are your favorite movies:</h1>
        {favorites.map(favorite => (
          <div key={favorite.id}>
            <h5>favorite.name</h5>
          </div>
          
        ))}
      </div>
    </div>
  )
}

I'm guessing that there's a way to put both API fetches in the same function. But I don't know how to. If anyone has any suggetions on how to do that I'd be happy to listen.

Thank you in advance.

You can make the calls in the same method and pass both data:

export const getServerSideProps = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  const resFav = await fetch(`${process.env.BACKEND_URL}/User/${id}/favorites`);
  const dataFav = await resFav.json();

  return {
    props: { user: data, favorites: dataFav },
  };
};

No need to declare getServerSideProps2

With a bit of your help and some tweaking I was able to solve it. Thank you all. No need to further comment for my sake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM