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?