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

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

Discovering a way to capture the space bar event in a number input field with JavaScript

Is there a way to capture space bar input with an onchange event in JavaScript? <html> <head> <script type = "text/javascript"> function lala(aa){ console.log(aa + " dasda"); } </script> </head> <body> <input ty ...

Utilizing Jquery to enhance table filtering functionality

I created a table listing various places, along with buttons to filter the list. The first filter is based on location (north, east, central, south, west) determined by postcode. The other filter is for "impress" which only displays places with a rating of ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

Deactivate the Submit button when the database field has been populated

My form includes a submit button. The Submit button should be disabled if the "price" for a specific product is already filled: PHP Code <?php $host="localhost"; $username="root"; $password=""; $db_name="ge"; $con=mysqli_connect("$h ...

Update D3 data, calculate the quantity of rows in an HTML table, and add animations to SVGs in the final

Attempting to update data in an HTML table using D3 has proven to be quite challenging for me. My task involves changing the data in multiple columns, adjusting the number of rows, and animating SVG elements in each row based on new data arrays. Despite tr ...

Encountering the error message "OAUTH_CALLBACK_ERROR invalid_client" while trying to authenticate with a custom provider through Next

I am experimenting with NextAuth to authenticate using a custom oauth2 provider (Whoop). However, after the login process is completed on the Whoop servers and I'm redirected back to my application, NextAuth throws the following error: [next-auth][err ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...

I am finding my program to be lacking efficiency. Is there a more concise method for solving this issue?

Starting off with my journey in Javascript, I am eager to tackle problems and enhance my skills. One challenge that came my way is the following question. Despite my efforts to solve it step by step, I feel like there might be room for improvement in my co ...

Type of Multiple TypeScript Variables

Within my React component props, I am receiving data of the same type but with different variables. Is there a way to define all the type variables in just one line? interface IcarouselProps { img1: string img2: string img3: string img4: string ...

Node.js: Capturing requests and responses for console logging

I'm currently working on a Hapi server using Good to log all requests and responses to the console. I've been able to successfully log responses but I'm facing issues with logging the body of the response, and for requests, I'm not gett ...

One issue with AngularJs is that it does not accurately display data that has been modified within

My MediaService service is being modified within a component. The data in MediaService is connected to another component, but any changes made in the first component are not reflected in the HTML of the second component. MediaService angular .module(&apo ...

Issue with interaction between jQuery AJAX and PHP login functionality

Currently, I am attempting to implement an inline login feature that triggers whenever the PHP $_SESSION['logged_in'] variable is not defined (this variable gets set when a user logs in). The challenge arises when I try to keep the user on the sa ...

The validation of form.$invalid appears to be malfunctioning when using the Angular UI date picker

There are two fields on the form, one for selecting a due date and another for entering a number. The due date field is a date picker where you can choose a date or manually enter a number to set the date. The create button gets enabled only when setting ...

Navigating through Next.js for slug URLs such as site.com/username

Can someone help me figure out how to create a profile page for each username, like site.com/jack or site.com/jill? I'll be pulling the username info from an API that also contains the user ID and email. I'm new to Next.js and would really appre ...

Creating a React website and running it locally on VSCode

Hey there! I'm currently facing some difficulties running this repository on my local machine. Can someone lend a hand? Check it out here! When trying to execute "npm run dev", I encounter the following errors: ⨯ ../../node_modules/next/dist/build/ ...

converting a JSON object into an array

I'm facing a challenge and unsure how to proceed. I have received JSON data from an API: https://i.stack.imgur.com/GdDUo.png When I log the data, this is what appears in the console: https://i.stack.imgur.com/GjSPW.png My goal is to extract the id ...

Trouble arises when attempting to parse multiple objects from a JSON file using JavaScript

Encountering JSON parsing issues with multiple JSON objects. JSON data is essential for JavaScript functionality. { "name": "Sara", "age": 23, "gender": "Female", "department": & ...