Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches.

The URL in the address bar appears as: http://localhost:3000/startpage?id=1

Below is the code snippet for the first API fetch:

import { useRouter } from "next/router";

export const getServerSideProps = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();
  // console.log(data);

  return {
    props: { user: data },
  };
};

The second API fetch is structured like this:

export const getServerSideProps2 = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}/favorites`);
  const data = await res.json();
  //console.log(data);

  return {
    props: { favorites: data },
  };
};

As a result, the page I am attempting to render displays the following content:

function StartPage( {user, favorites} ){
  return (
    <div>
      <div className={styles.formGroup}>
        <h1>Welcome {user.name}</h1>
      </div>
      <div>
        <h1>These are your favorite movies:</h1>
        {favorites.map(favorite => (
          <div key={favorite.id}>
            <h5>favorite.name</h5>
          </div>
          
        ))}
      </div>
    </div>
  )
}

I believe there might be a way to combine both API fetches within one function, but I am unsure of the process. Any suggestions or insights on how to achieve this would be greatly appreciated.

Thank you in advance.

Answer №1

To efficiently retrieve data, you can consolidate the calls within a single method and pass both datasets:

export const getServerSideProps = async (context) => {
  const { id } = context.query;

  const res = await fetch(`${process.env.BACKEND_URL}/User/${id}`);
  const data = await res.json();

  const resFav = await fetch(`${process.env.BACKEND_URL}/User/${id}/favorites`);
  const dataFav = await resFav.json();

  return {
    props: { user: data, favorites: dataFav },
  };
};

Avoid defining an additional function like getServerSideProps2

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

Input field modified upon focus

I am currently using selectize js in my section to create a select box. My goal is to make the input editable after selecting an option when it is focused on. Check out the live demo: live demo HTML <label>Single selection <select id=" ...

The response from the XHR object is coming back as "Object Object

Recently, I've been faced with the challenge of working with an API that provides articles. Within the array returned by the API, there are attributes like author, title, and description. However, despite my efforts, each time I attempt to retrieve th ...

The component you are trying to import requires the use of useState, which is only compatible with a Client Component. However, none of the parent components have been designated with the "use client" tag

I encountered an issue with the code snippet below in my Next.js app directory when utilizing useState: When trying to import a component that requires useState, I received this error message. It seems that the parent components are marked as Server Co ...

Implementing a Scroll Bar within a Stack Component in Material UI

I've developed a component and now I'm looking to enable scrolling when it expands beyond the screen width <Stack direction="row"> <Stack gap={1} overflow="auto"> {fields.map((el, i) => ( ...

The Colorbox feature showcases images in their binary data format

I'm currently experimenting with using Colorbox to enhance a website that is being built with Backbone.js. Within my code, I have a straightforward image tag set up like this: <a class="gallery" href="/document/123"><img class="attachment-pr ...

Crop and upload images asynchronously using Node.js

I need to resize an image into multiple sizes and then upload them to AWS S3. The specific resizing dimensions are stored in an array. To accomplish this, I am utilizing the async waterfall method along with the series method. async.each(crop_sizes, func ...

Setting default values for JSON objects by analyzing the data of other objects within the array

I've been grappling with this issue for about 6 days now, so please bear with me if my explanation is a bit convoluted. I'm using NVD3 to showcase graphs based on data retrieved from BigQuery. While the data and graph setup are correct, the probl ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist. My current goal is to iterate over this array, extract each URL, and then make additional API calls to retri ...

Using JavaScript to empty input field when switching focus between input fields

I am experiencing an issue with clearing a input number field. Here is the code snippet in question: <input class="quantity_container" v-model="length.quantity" type="number" pattern="[0-9]*" inputmode="numeric" onfocus="if (this.value == &ap ...

Angular is encountering a circular dependency while trying to access a property called 'lineno' that does not actually exist within the module exports

I am working on an Angular project and using the Vex template. My project utilizes Angular 9 and Node.js v15.2.0. Every time I run the project with the command ng serve -o, it displays a warning message. https://i.stack.imgur.com/8O9c1.png What could b ...

Stop users from being able to input line breaks by pasting

I am currently facing a challenge with my code. Within the code, I have included a textarea where users can input the title of an article, and I want this title to be restricted to only one line. To achieve this, I created a script that prevents users from ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Is there a way to modify the CSS or add custom styling within an iframe form?

Currently I am working on the following page: , where an embedded javascript form called infusionsoft (iframe form) needs to be made responsive at the request of my client. I'm wondering if there is a way to override the css or inject custom styles i ...

What is the best way to securely showcase images stored in Azure blob storage within an img tag?

I have a form on my website where users can upload images. When an image is uploaded, it gets saved under a new container with a random unique ID. On another page, I want to display that image securely without exposing its location or container name to use ...

The Nextjs next-auth implementation with URL '/api/auth/callback/cognito' encountered a 502 Bad Gateway error while in production

I'm facing a challenge while trying to deploy a nextjs app that utilizes 'next-auth' with AWS Cognito. Interestingly, the app runs smoothly when tested locally using either next dev or next start. However, upon deploying it on the producti ...

Unable to update values in Google Sheets using the node.js API

I have been working on a node.js project that involves extracting the location of a cell based on a person's name and date. While I am able to determine this information easily, I encounter difficulties when trying to update the cell using the .update ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...

What could be the reason why this LESS CSS is not taking effect?

Why won't this stylesheet load properly? The desired background color is supposed to be similar to cadetblue. You can view my page with the linked home.less.css at: ...