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

The conceal feature doesn't appear to be functioning properly on jQuery Mobile

I am facing an issue with a small mobile app built using jQuery Mobile. Within a div, I have three buttons and other content. My goal is to hide these three buttons if the user's device is running on Windows (WP). The buttons are defined as follows: ...

Height of the div dynamically increases upwards

Just a quick question - is there a way to make position: fixed divs at the bottom of an element (such as the body) grow upwards as content is dynamically added? Maybe something like anchor: bottom or increase: up? I'm thinking that using JavaScript m ...

Customize the <td> column based on values and rows. Modify the current jQuery code

This code snippet contains an HTML table that dynamically populates based on the dropdown selection. The script included in the code highlights the best and worst values in the table by changing their background color to green and red, respectively. & ...

Enhancing Label and Input Elements with Dynamic CSS through jQuery Values

Edit : I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Framework I cannot remove it. I'm trying to apply dynamic styling to the input and label elements in my HTML using jQuery. However ...

Insert a page break after content for desktop browsers

Is it possible to control the display of sections on different screen sizes? I have a page that looks good on 15" laptops, but larger resolutions cause the next section to appear on the first screen. Is there a way to show the next section only on th ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Utilize HighCharts to seamlessly implement multiple series with the help of AJAX requests

I am facing an issue with plotting the performance results on HighCharts using AJAX. The problem lies with the .addSeries API call not functioning correctly. I need assistance in determining if my approach is correct. $(function () { $('#chart3&a ...

Creating a hierarchical tree structure from tabular data with JavaScript ECMAScript 6

Seeking a JavaScript algorithm utilizing ECMAScript 6 features to efficiently convert JSON table data into a JSON tree structure. This approach should not employ the traditional recursive algorithm with ES5, but rather emphasize a functional programming me ...

Having trouble getting the timer function to execute upon page load in JavaScript

My goal is to have my basic timer function activate when the page loads. However, I'm encountering issues with it not working as intended. I suspect there may be an error in the if else loop, possibly here: setTimeout(function(tag, sec), 1000);. How c ...

What is the proper method for adding a file to formData prior to sending it to the server using a

I came across this tutorial on FormData, but I'm still trying to grasp how the formData object functions. Input Form Example: https://i.stack.imgur.com/h5Ubz.png <input type="file" id="file-id" class="w300px rounded4px" name="file" placeholder=" ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

position property in div element disrupts slider functionality

I've been working on incorporating a simple slider into my website and stumbled upon this example on jsfiddle My goal is to have the slider positioned "relative" within my site, but when I change the CSS to position: relative;, the slider no longer ...

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...

PhoneGap fails to fire the ondeviceready event within 5 seconds

Currently, I am in the process of debugging my PhoneGap app using Weinre and facing some persistent errors... The 'deviceready' event has not fired even after 5 seconds. Channels are not firing: onPluginsReady, onCordovaReady, onCordovaConnecti ...

Problem with jQuery: Modifications to CSS made before an each loop are only applied afterwards

Below is some code I am working with: LoadingImage.show("#contentpage", urlStk.LoadImg); var errors = 0; var ComponentToUpdate = new Array(); var storedItems = JSON.parse(localStorage.getItem("Components")); $(".myDataGridRow").each(function () { er ...

Tips for transferring v-model data between components

I am working with a parent form component and a child component, both located in separate files. I am using the Quasar Framework components. How can I pass data from the parent to the child component using v-model? Parent Component <template> < ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

Conceal the Div containing the specified class

I was hoping to hide the first DIV if the second DIV is displayed on the front end, and vice versa upon page load. If the first DIV is set to 'block,' then the second DIV should be set to 'none.' And If the second DIV is set to &apos ...