How can one retrieve data from two distinct API routes within a Next.js application?

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);
      }

Answer №1

If you want a simpler solution, you don't have to wait for the first request to finish before starting the second one. You can use Promise.all to simultaneously fetch data from both endpoints.

export async function getServerSideProps({ query: { className } }) {
  // Set up promises for fetching required data
  const promises = [
    fetch(`http://localhost:3000/api/admin/classes/${className}`).then(res => res.json()),
    fetch(`http://localhost:3000/api/classes/${className}/subjects`).then(res => res.json()),
  ];

  // Use Promise.all to wait for all promises to resolve
  const [classDetail, subjects] = (await Promise.all(promises)).map(p => p.data);

  return { props: { classDetail, subjects } };
}

It seems like your issue with the second request lies in trying to destructure the data2 attribute using

const {data2} = await res2.json()
. Instead, focus on retrieving the data attribute from both responses, as shown in my example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective way to determine which radio button is currently selected in a group with the same name using JQuery?

<form class="responses"> <input type="radio" name="option" value="0">False</input> <input type="radio" name="option" value="1">True</input> </form> Just tested: $('[name="option"]').is(':checked ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

What is the best way to include a div element with a dynamic animation on a webpage?

I'm attempting to create a laser beam that can shoot enemies on the screen, much like in classic games such as Space Invaders or Galaga. However, I am encountering difficulties getting the laser to move when I click the button. Below is the code I hav ...

Enhancing the "click-to-pause" feature with jQuery Cycle

Is it possible to delay the click-to-pause feature on my slideshow until after the first slide transition? Currently, the slideshow becomes clickable as soon as the DOM is ready, which is too early for my liking. Here is a simplified version of my current ...

Is it possible to delete browsing history in Express using node.js?

Upon user login, I store user information in browser sessions on the client side (using Angular) like this: $window.sessionStorage.setItem('loggedInUser', JSON.stringify(val)); For logout authentication on the backend (using Passportjs), I have ...

Ensure that only valid numbers can be inputted into an HTML number type field

My input number is as follows: <input type="number" id="quantity" name="quantity" (change)="firstRangePointChanged($event)" > I need to ensure that users cannot input invalid values like --99 (--) instead of ...

GetServerSideProps function yielding varied prop values

I'm currently exploring NextJS and delving into SSR. I've been struggling to grasp the functionality of getServerSideProps(). It seems that it should replace useState in order to be rendered on the backend, but I'm receiving different props ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

React Router 4 - Optimizing Component Refresh by Remounting Instead of Re-Rendering

I am currently in the process of configuring a React project that utilizes React Router 4 ("react-router-dom": "^4.3.1"). Within this project, I have implemented a SideBar, a NavBar, and the main content section of the application which changes based on th ...

Error in Next.js due to component not being rendered despite being present

useSession((s) => s.user) will either return a user object or null. The index page should display the user's name, and is surrounded by a PrivatePageProvider that redirects the client if the user object is null. However, an error occurs as IndexPag ...

Optimal Method for Organizing Items in Express.js Using Mongodb

Can you share your insights on the best practices for sorting objects in expressjs + mongodb(mongoose) web applications? Imagine we have a Product model with four attributes: var ProductSchema = new mongoose.Schema({ name: String, // "Summer T-sh ...

AJAX loading footer content before images are fully loaded

I am a beginner when it comes to ajax and I'm facing an issue where the footer loads before the images, causing the images to overlap the footer. The problem is illustrated in the image below. <!doctype html> <html lang="en"> <head ...

The issue of the back button not functioning in the React Multi-level push menu SCSS has

I have been developing a mobile-friendly Multi-level push navigation menu for my website using dynamically generated links based on projects from my GitHub account. I found a push menu on CodePen here and am in the process of integrating it into React inst ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

I attempted to implement a login feature using a prompt within a React application, but I encountered a situation where the browser asked me for the same details twice. How can I resolve

https://i.sstatic.net/nhuC1.png I've been working on adding a login feature to my webpage where the content is only rendered if users input valid credentials. However, I've encountered a problem where the browser prompts for credentials twice in ...

Injecting windows in Angular

Is there a way to prevent the Angular instance from injecting into the global (window) scope when required and bundled with webpack or any other module bundler? Upon inspection, I discovered that the current main Javascript file in the Angular npm package ...

Looking for assistance with retrieving all files from a directory based on their file extensions in JavaScript

Looking for a way to gather all the '.txt' files from a folder that also contains a 'backup' folder, and moving them into the 'backup' folder using Node.js. If you have any suggestions, please share. Thanks! Best regards, M ...

Ensuring that md-select(s) created through ng-repeat are linked to the same model

<div ng-repeat="(key, value) in dataSet | groupBy: 'partner.partnerName'"> <md-select ng-model="userName" placeholder="{{ key }}" class="partnerUser" > <md-option >{{ key }} </md-option> <md-option ng-repe ...