I’m trying to loop through a fetch array of 3 posts and display the titles of each. However I can only seem to see the first post (1) on the page. I’m not sure if I got the loop working properly?
Here is my current code:
export async function getServerSideProps() {
const posts = [1, 2, 3]
for (const id of posts) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
const data = await res.json()
return { props: { data } }
}
}
const Page = ({data}) => {
return (
<div className="main-container">
<p>{data.title}</p>
</div>
)
}
export default Page
>Solution :
The problem is that you are returning inside the for loop.
So the object will be returned after the first iteration.
Try to store the results in a separate array and return outside the loop.
Then display the different titles mapping on the property received:
export async function getServerSideProps() {
const posts = [1, 2, 3];
const postList = [];
for (const id of posts) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
postList.push(await res.json());
}
return { props: { data: postList } };
}
const Page = ({ data }) => {
return (
<div className='main-container'>
{data.map(post => <p>{post.title}</p>)}
</div>
);
};
export default Page;