DEV Community

Joney Spark
Joney Spark

Posted on

After Pushing a Array Element in react.js it's looping infinitely in useEffect. Help plz

I have pushed some image elements in object array it's working fine but how to update the state?

const url = "https://jsonplaceholder.typicode.com/posts";
        const [posts, setPosts] = useState([]);

        const postsMap = posts.map(post => {
            return {...post, "image": `image-${post.id}.jpg`}
        })

        console.log("Added Post Image", postsMap);

        useEffect(()=>{
            fetch(url)
            .then(res => res.json())
            .then(data => {
                setPosts(data)
                console.log(data);
            })

        }, [postsMap]);

Top comments (4)

Collapse
 
webintex profile image
Dennis • Edited

try put the map function when the fetch promise fullfils. You should never manipulate a state object directly.

Try (not tested, wrote it on my phone):

const url = "jsonplaceholder.typicode.com/posts";
const [posts, setPosts] = useState([]);
useEffect(()=>{
fetch(url)
.then(res => res.json())
.then(data => {
const posts = data.map(post => {
return {...post, "image": image- ${post.id}.jpg}
});
setPosts(posts);
console.log(posts);
})
}, []); // dependency array empty to only run once on mount

Hope this helps

Collapse
 
joneyspark profile image
Joney Spark

That's really fantastic. I'm very grateful to you. Thanks a lot. It's really a fantastic place dev.to. people are so helpful. Thanks a lot

Collapse
 
justusburger profile image
Justus Burger

But it also does not make sense to put postsMap as a dependency of the useEffect, since it is not used in the effect. You should replace it with setPosts, as this is used in the effect.

useEffect(() => {
...
}, [setPosts]);

Collapse
 
justusburger profile image
Justus Burger

The posts.map call creates a new array on every render. This causes the useEffect statement to run again since the dependency postsMap changed.

const postsMap = useMemo(() => posts.map..., [posts]);

Use can wrap the posts.map in a useMemo to make it recalculate only when posts changed.