Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS getServerSideProps() with multiple fetch requests

Is there a way to fetch data from multiple API routes in a single getServerSideProps()?

I have a table that I need to show data from multiple MongoDB collections and trying to figure out how to pull that data in.

Essentially, I need to combine these two functions but can't seem to find the best way to go about it.

export async function getServerSideProps() {
  const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`);
  const { data } = await res.json();
  return { props: { operations: data } };
}

export async function getServerSideProps() {
  const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute2}`);
  const { data } = await res.json();
  return { props: { incidents: data } };
}

I may be attempting something dumb so a pointer in the right direction is greatly appreciated!

like image 411
aglasier Avatar asked Dec 07 '22 09:12

aglasier


1 Answers

Did you try the following?

export async function getServerSideProps() {
  const [operationsRes, incidentsRes] = await Promise.all([
    fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`), 
    fetch(`${process.env.APP_DOMAIN}/api/${apiRoute2}`)
  ]);
  const [operations, incidents] = await Promise.all([
    operationsRes.json(), 
    incidentsRes.json()
  ]);
  return { props: { operations, incidents } };
}

Promise.all will trigger both requests and they will return the resolved value for both fetch calls when completed

like image 110
luckongas Avatar answered Dec 11 '22 12:12

luckongas