'useEffect goes in an infinite loop. How to fix this?
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])
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Khant |
| Solution 2 | huzzzus |
