boscode
boscode

Reputation: 89

Loop with fetch - React

I'm trying to loop through the API to fetch data from all 5 pages into my setPosts array. I would like all the data grouped together, rather than nested into arrays. The image below shows how the data comes through now, with index 20+ being pages 2, 3, 4, etc. that I would like to display like the info before it.

  const getPosts = () => {
        for (let i = 1; i < 6; i++) {
          fetch(`/api/posts?page=${i}`)
          .then((res) => res.json())
          .then((data) => setPosts(prevPosts => [...prevPosts,  data.posts]))
          .catch((error) => console.log('Error fetching posts', error));
        } 
      };

enter image description here

Upvotes: 1

Views: 940

Answers (1)

Sobhan Jahanmard
Sobhan Jahanmard

Reputation: 890

This part of code seems fishy. Though the information here is a bit lacking. Deploy these changes to see if this works. The data that you fetch is an Array of Objects. you want to add it to your previous Array of Objects so do this:

.then((data) => setPosts(prevPosts => [...prevPosts, ...data]))

Upvotes: 2

Related Questions