What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section:

export default async (req, res) => {
  const { query: { className }, method } = req;

  switch (method) {
    case "GET":
      try {
        const classDetail = await Class.findOne({title: className});
        if (!classDetail) {
          return res.status(400).json({ success: false });
        }
        res.status(200).json({ success: true, data: classDetail });
      } catch (error) {
        res.status(400).json({ success: false });
        console.log(error);
      }
      break;
    default:
      res.status(400).json({ success: false });
  }

On my [className] page, I am attempting to retrieve data from the following API endpoint:

http://localhost:3000/api/admin/classes/${className}
. However, when I log the response, it shows as undefined.

export async function getServerSideProps({ query: { className } }) {
  const res = await fetch(`http://localhost:3000/api/admin/classes/${className}`)
    .then(() => console.log(`first get request sent: `));

  // const { data } = await res.json();
  console.log(res)

  return { props: { classDetail: 1 } };
}

Interestingly, when I make the same GET request using Postman with the endpoint

http://localhost:3000/api/admin/classes/class-3
, it returns the expected data. Why am I not receiving the same data within getServerSideProps?

{
    "success": true,
    "data": {
        "_id": "62f6858ea26fbb47b3cc0563",
        "title": "class-3",
        "classImageURL": "http://res.cloudinary.com/nhnasem/image/upload/v1660323222/HELP_ME_ewcr5t.png",
        "imageWidth": "1555",
        "imageHeight": "2000",
        "__v": 0
    }
}

What could be causing this issue and how can I resolve it?

Edit: I also tested it with the JSONPlaceholder API, but encountered the same 'undefined' result.

Edit 2: Handling requests for two APIs

export async function getServerSideProps({ query: { className } }) {
  const res = await fetch(
    `http://localhost:3000/api/admin/classes/${className}`
  );

  const {data} = res.json()

  const res2 = await fetch(
    `http://localhost:3000/api/admin/classes/${className}/subjects`
  );

  const {data} = await res2.json()   // this won't work as it was already called and declared before
  return { props: { classDetail: data, subjects: data} }; 
}

Answer №1

The issue arises from the additional .then() you have included in your fetch call.

When you append a .then() to a promise chain, it takes the result of the initial fetch as its argument and is expected to return the desired result of a promise. In this scenario, you are not returning anything, leading to the presence of undefined in your res variable. Instead, it is recommended to return the original outcome:

const res = await fetch(`http://localhost:3000/api/admin/classes/${className}`)
    .then((res) => { console.log(`first get request sent: `); return res; });

or alternatively eliminate

.then(() => console.log(`first get request sent: `));

UPDATE If both responses contain an object with a data property, you cannot destructure both outcomes using the same variable name:

const {data} = await res.json()
const {data} = await res2.json();

In such cases, specify the variable that should hold the data:

const {data: classDetail} = await res.json()
const {data: subjects} = await res2.json();

return { props: { classDetail, subjects} };

or provide more clarity:

const json = await res.json()
const json2 = await res2.json();

return { props: { classDetail: json.data, subjects: json2.data} };

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

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

What could be the reason behind Strapi v4 only displaying the initial 25 articles? Discussing Next.js and React

I've encountered a peculiar bug while working with Strapi v4. The technology stack being used is React and Next.js I've set up a dynamic pagination system with the format /page/[slug]. It's functioning almost perfectly, except for one majo ...

Issues with CKEDITOR in Internet Explorer when multiple instances are used with different configuration files

My current challenge involves placing multiple CKEDITOR instances on a single page, each loading a different configuration file. While it functions correctly in Firefox (FF), Internet Explorer (IE) seems to apply the config file from the last instance on t ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

Is there a way to verify the presence of a service worker on a specific URL?

Is there a way for me to determine if external websites have a 'service-worker' or not? Here is what I think could work: Extract all the JavaScript files from the given URL Look for the string 'sw.js' (I am not entirely sure how to ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

State of the Browser - JavaScript/jQuery

Looking for a method to identify when my browser is loading and display a loading icon. Is this approach appropriate, or should I follow a more common practice to achieve the same goal? Edit: This feature will be implemented on one of my websites during ...

Uncertainties surrounding the use of JSON data versus a JavaScript object

As a newcomer to programming, I have ventured into Stack Overflow and W3schools to enhance my skills. Recently, I created a small project for educational purposes. One dilemma is bothering me - is the JSON file I generated actually in proper JSON format o ...

Converting dates to time in amCharts v3: A step-by-step guide

I am looking to exclusively show "6 AM" on my X AXIS, rather than displaying 2019-09-05 06:00:00 Please refer to my code sample at https://jsfiddle.net/uwtz3p4h/ Is it feasible to only display the time? I have searched through their documentation but co ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

What is the process for obtaining the URL type for Higher Order Components in NextJS?

When building a component with a Link, I am struggling to properly define the type for the href prop. import React from "react; import Link, { LinkProps } from "next/link"; type MyComponentProps = { href: Pick<LinkProps, "href&quo ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...

Dealing with multiple submit buttons in a form with Angular JS: best practices

I'm using AngularJS and I have a form where the user can enter data. At the end of the form I want to have two buttons, one to "save" which will save and go to another page, and another button labeled "save and add another" which will save the form an ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

How can I prevent event propagation in Vuetify's v-switch component?

Currently, I am working with Vuetify and have incorporated the use of v-data-table. Whenever I click on a row within this data table, a corresponding dialog box represented by v-dialog should open. Additionally, each row contains a v-switch element. Howeve ...