简体   繁体   中英

Why does the fetch request returns an undefined data in Nextjs?

This is the code in the api sections for my GET request:

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

In my [className] page, I want to fetch the data from http://localhost:3000/api/admin/classes/${className} API. I console logged the response, but it returns undefined for some reason.

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

But when I send the same get request from postman using http://localhost:3000/api/admin/classes/class-3 API, it sends me the following data. I'm not getting the data from 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
    }
}

Why is this happening? And how can I resolve the issue? Edit: I tried it with jsonplaceholder API. The result is the same undefined.

Edited 2: For two API

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()   // it won't do, because it was called  
                                     // and initialized before
  return { props: { classDetail: data, subjects: data} };  // ???????????
}

The reason is that extra .then() that you added to your fetch call.

When you add .then() to a promise chain, it receives the result of fetch as its argument and is supposed to return whatever should be the result of a promise. In your case, you're not returning anything, hence the undefined you get in your res variable. Instead, you should return the original result:

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

or simply remove

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

UPDATE If both requests return an object with data property, you can't simply destructure both results due to duplicated variable name:

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

What you can do, is to provide the name of a variable where data should be assigned:

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

return { props: { classDetail, subjects} };

or even be more explicit:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM