简体   繁体   English

如何在 Next.js 中进行依赖获取 API 调用

[英]How to make dependent fetch API calls in Next.js

Im beginner and trying to better understand API calls.我是初学者并试图更好地理解 API 调用。

I want to make a call to a bible api that retrieves all books.我想打电话给检索所有书籍的圣经 api。 I then need to make a call to the same api with the book # to retrieve all chapters for requested book.然后我需要用书号调用相同的 api 以检索请求书的所有章节。

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.为此,我制作了一个实用程序 function 循环浏览书籍并返回章节。 This is where it breaks.这就是它崩溃的地方。

I was able to retrieve the books and display them.我能够检索书籍并展示它们。 But I am stuck as to how the make the second API call.但我不知道如何进行第二个 API 调用。 I keep getting an error that I cannot serialize object Promise.我不断收到无法序列化 object Promise 的错误。

Also what is the best way to console log here in Next?另外,在 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;
}

The problem is that you're pushing promises into an array, not the values inside the promises.问题是您将 Promise 推送到数组中,而不是 Promise 中的值。 Instead of using that array, you can return in the map directly, and use Promise.all to get the values out.您可以直接在 map 中返回,而不是使用该数组,然后使用Promise.all来获取值。 (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:为了清楚起见,我将getBooks调用提升到它自己的 function 中,但重要的变化是getChapters的 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,
    },
  }
}

You can test this in plain Node (assuming node-fetch or a similar package) or the browser outside of Next with something like:您可以在普通节点(假设node-fetch或类似包)或 Next 之外的浏览器中测试它,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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