Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to loop through fetch array and display results?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading