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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With