1

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

1 Answer 1

2

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]))
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.