Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps
function.
The first dataset that I require can be found at the endpoint
http://localhost:3000/api/admin/classes/${className}
.
Similarly, the second set of data is located at
http://localhost:3000/api/admin/classes/${className}/subjects
.
Although fetching data from a single API works seamlessly, I encountered difficulties when attempting to access both APIs using the code inside getServerSideProps.
I envision structuring the retrieved data as follows:
export default function classPage({ subjects, classDetail }) {}
. Therefore, ideal return props from getServerSideProps would resemble: return { props: {classDetail: data, subjects: data2} }
, should it prove feasible.
export async function getServerSideProps({ query: { className } }) {
const res = await fetch(
`http://localhost:3000/api/admin/classes/${className}`
);
const res2 = await fetch(`http://localhost:3000/api/classes/${className}/subjects`);
const { data } = await res.json();
const {data2} = await res2.json();
return { props: { classDetail: data, subjects: data2 } };
}
Here is an excerpt of the api GET request code:
try {
const subjectDetail = await Subject.find({}).populate('classDetail');
res.status(200).json({success: true, data: subjectDetail});
} catch (error) {
res.status(400).json({success: false});
console.log(error);
}