最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Fetching data in loop next js - Stack Overflow

programmeradmin0浏览0评论

I am attempting to use the data from 1 endpoint to call another endpoint that is filtered by id. I am planning on fetching both calls using getServerSideProps and passing the data to another ponent.

The first call will return an array of categories which then I am attempting to loop and fetch articles that is filtered by id.

I am able to successfully get back the array of categories but when I am attempting to loop and fetch articles I am getting a value of undefined How can I achieve this?

Here is an example of my index.js

import ArticleList from "../../ponents/ArticleList";


const Index = ({ categories, articles }) => {


  return (
    <>
      <ArticleList categories={categories} articles={articles} />
    </>
  )
}

export async function getServerSideProps (context) {
   // console.log('index - getserversideprops() is called')
   try {
     let articles = []
    let response = await fetch('/categories')
    const categories = await response.json()

    for (let i = 0; i < categories.results.length; i++) {
      response = await fetch (`/articleid/` + categories.results[i].id)
      articles = await response.json()
    }

    console.log(articles,'33')


    if (!categories ) {
        return {
            notFound: true,
        }
    }

    return { 
      props: { 
        categories: categories,
        articles: artices
      }
    }
  } catch (error) {
      console.error('runtime error: ', error)
  }
}

export default Index

Here is an example of my console.log(categories.results) array:

[ {
"id": 2,
"name": "Online"
},
{
"id": 11,
"name": "Retail"
},
{
"id": 14,
"name": "E-Commerce"
}]

I am expecting articles to be 3 separate arrays of data. Is this something that is possible if I am passing the data to another ponent? If not what will be a better way of handling this?

I am attempting to use the data from 1 endpoint to call another endpoint that is filtered by id. I am planning on fetching both calls using getServerSideProps and passing the data to another ponent.

The first call will return an array of categories which then I am attempting to loop and fetch articles that is filtered by id.

I am able to successfully get back the array of categories but when I am attempting to loop and fetch articles I am getting a value of undefined How can I achieve this?

Here is an example of my index.js

import ArticleList from "../../ponents/ArticleList";


const Index = ({ categories, articles }) => {


  return (
    <>
      <ArticleList categories={categories} articles={articles} />
    </>
  )
}

export async function getServerSideProps (context) {
   // console.log('index - getserversideprops() is called')
   try {
     let articles = []
    let response = await fetch('https://example.api/categories')
    const categories = await response.json()

    for (let i = 0; i < categories.results.length; i++) {
      response = await fetch (`https://example.api/articleid/` + categories.results[i].id)
      articles = await response.json()
    }

    console.log(articles,'33')


    if (!categories ) {
        return {
            notFound: true,
        }
    }

    return { 
      props: { 
        categories: categories,
        articles: artices
      }
    }
  } catch (error) {
      console.error('runtime error: ', error)
  }
}

export default Index

Here is an example of my console.log(categories.results) array:

[ {
"id": 2,
"name": "Online"
},
{
"id": 11,
"name": "Retail"
},
{
"id": 14,
"name": "E-Commerce"
}]

I am expecting articles to be 3 separate arrays of data. Is this something that is possible if I am passing the data to another ponent? If not what will be a better way of handling this?

Share Improve this question asked Dec 8, 2021 at 1:55 kurtixlkurtixl 4196 silver badges18 bronze badges 1
  • 4 You overwrite articles in each iteration of the loop. You should probably push to an array. articles.push(await response.json(). – nlta Commented Dec 8, 2021 at 2:01
Add a ment  | 

1 Answer 1

Reset to default 5

Try Promise.all

export async function getServerSideProps(context) {
  try {
    const categories = await fetch('https://example.api/categories').then((response) => response.json());

    if (!categories) {
      return { notFound: true };
    }

    const articles = await Promise.all(
      categories.results.map((result) =>
        fetch(`https://example.api/articleid/` + result.id).then((response) => response.json())
      )
    );

    const props = { categories, articles };

    return { props };
  } catch (error) {
    console.error('runtime error: ', error);
  }
}

The code will be clean.

发布评论

评论列表(0)

  1. 暂无评论