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));
}
};
CodePudding user response:
This part of code seems fishy. Though the infromation here is a bit lacking. deploy these changes to see if this work. The data taht you fetch is an array of objects. you want to add it to your previous array of objects. So:
.then((data) => setPosts(prevPosts => [...prevPosts, ...data]))