如何在Next.js中进行依赖获取API调用 [英] How to make dependent fetch API calls in Next.js

查看:109
本文介绍了如何在Next.js中进行依赖获取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.

此外,在下一步"中控制台日志的最佳方法是什么?我不确定如何查看返回的内容.

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

这是我到目前为止所拥有的:

Here is what I have so far:

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-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中进行依赖获取API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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