【问题标题】:How to make dependent fetch API calls in Next.js如何在 Next.js 中进行相关的 fetch API 调用
【发布时间】:2021-04-28 17:44:51
【问题描述】:

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

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

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

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

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

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

这是我目前所拥有的:

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

【问题讨论】:

  • 使用 async/await 而不是 then 链(就像你已经拥有的代码一样)

标签: javascript reactjs fetch next.js


【解决方案1】:

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

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 之外的浏览器中进行测试,如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2020-08-24
    • 2018-11-04
    • 2022-10-24
    • 2020-11-09
    相关资源
    最近更新 更多