Skip to content
Advertisement

Fetching data in loop next js

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 component.

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 "../../components/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 component? If not what will be a better way of handling this?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement