Home > Mobile >  useEffect goes in an infinite loop. How to fix this?
useEffect goes in an infinite loop. How to fix this?

Time:04-02

Please alter this code so that useEffect does not keep calling itself again and again. Here, I am fetching data from the backend and updating state within the useEffect, which itself is the dependency. Is there some easy way to fix it?

My use case: I use a form to add a post and once I submit the form, I want it to show the updated list of posts right away. 'Posts' is a component where the updated list of posts are passed as props and each individual post is rendered within component 'Post'. So, I want to pass the updated list of post to 'Posts' once the form is submitted

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink   '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, [posts])

CodePudding user response:

useEffect(() => {
    async function readPosts(){
      try {
        const res = await axios.post(backendLink   '/post/profile/read');
        setPosts(res.data.posts);
      } catch (err) {
        console.log(err);
      }
    }
    readPosts();
  }, []) // Change here

CodePudding user response:

This is whats happening right now in your code.

useEffect fires when the "posts" value change. the useEffect changes the "posts" which triggers useEffect because useEffect changed "posts"

this is an infinite loop. remove [posts] from dependency and find a workaround.

  • Related