3

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?

1
  • 4
    You overwrite articles in each iteration of the loop. You should probably push to an array. articles.push(await response.json(). Commented Dec 8, 2021 at 2:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.