Asked By: Anonymous
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!!
Solution
Answered By: Anonymous
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