如何在 Next.js 中进行相关的 fetch API 调用 [英] How to make dependent fetch API calls in Next.js

查看:30
本文介绍了如何在 Next.js 中进行相关的 fetch API 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者,正在努力更好地理解 API 调用.

Im beginner and trying to better understand API calls.

我想调用一个检索所有书籍的圣经 API.然后我需要调用与书相同的 api # 来检索请求书的所有章节.

I want to make a call to a bible api that retrieves all books. I then need to make a call to the same api with the book # to retrieve all chapters for requested book.

然后我想显示书籍列表以及章节.

I then want to display a list of the books along with the chapters.

为此,我制作了一个实用函数,可以循环阅读书籍并返回章节.这就是它崩溃的地方.

To this I made a utility function that loops through the books and returns the chapters. This is where it breaks.

我能够检索书籍并展示它们.但我对如何进行第二个 API 调用感到困惑.我不断收到无法序列化对象 Promise 的错误.

I was able to retrieve the books and display them. But I am stuck as to how the make the second API call. I keep getting an error that I cannot serialize object Promise.

此外,在 Next 中控制台登录的最佳方式是什么?我不知道如何查看它被退回的内容.

Also what is the best way to console log here in Next? Im not sure how to go about seeing what its being returned.

这是我目前所拥有的:

export default function Home(props) {
  console.log(props);
  return (
    <div className="container">
      <div>{/** display books & chapters */}</div>
    </div>
  );
}

export async function getStaticProps() {
  // get all books
  const reqBooks = await fetch(`https://getbible.net/v1/web/books.json`);
  const resBooks = await reqBooks.json();
  // convert to array of objs
  const books = await Object.entries(resBooks);


  const chapters = await getChapters(books);

  return {
    props: {
      books,
      chapters,
    },
  };
}

// utility... loop through books and make api calls to get chapters for each book
async function getChapters(books) {
  const chaptersArr = [];

  books.map((item, idx) => {
    //
    let url = item[1].url;
    let bookChapters = fetch(url).then(response => response.json().then(data => data));
    arr.push(bookChapters);
  });
  return chaptersArr;
}

推荐答案

问题是您将 Promise 推送到数组中,而不是 Promise 中的值.您可以直接在地图中返回,而不是使用该数组,并使用 Promise.all 来获取值.(您也可以使用数组,但由于您使用的是地图,因此不需要它).为了清楚起见,我将 getBooks 调用提升到它自己的函数中,但重要的变化是地图中的 getChapters 发生了什么:

The problem is that you're pushing promises into an array, not the values inside the promises. Instead of using that array, you can return in the map directly, and use Promise.all to get the values out. (You could use the array too, but there's no need for it since you're using a map). I lifted the getBooks call into its own function for clarity here, but the important change is what's going on in getChapters in the map:

async function getBooks () {
  const res = await fetch('https://getbible.net/v1/web/books.json')
  const json = await res.json()
  return Object.entries(json)
}

async function getChapters (books) {
  const chapters = await Promise.all(
    books.map(async (item) => {
      const url = item[1].url
      const res = await fetch(url)
      const json = await res.json()
      return json
    })
  )

  return chapters
}

export async function getStaticProps() {
  const books = await getBooks()
  const chapters = await getChapters(books)

  return {
    props: {
      books,
      chapters,
    },
  }
}

您可以在普通 Node(假设 node-fetch 或类似的包)或 Next 之外的浏览器中进行测试,如下所示:

You can test this in plain Node (assuming node-fetch or a similar package) or the browser outside of Next with something like:

getStaticProps().then(data => {
  console.log(JSON.stringify(data, null, 2))
})

这篇关于如何在 Next.js 中进行相关的 fetch API 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆