Reputation: 89
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));
}
};
Upvotes: 1
Views: 940
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 Object
s. you want to add it to your previous Array
of Object
s so do this:
.then((data) => setPosts(prevPosts => [...prevPosts, ...data]))
Upvotes: 2