I'm trying to fetch data from an API every time a user creates a new post. And I know that if you want to make the request happen when the data changes you can use this:
const [tweets, setTweets] = useState([])
useEffect(() => {
api.get('tweets').then(response => setTweets(response.data))
}, [tweets])
It works, and I don't need to refresh the page to see the new post that has been created. But when I go to Inspect in my app and then to Network, I can see that infinite amounts of GET requests happen, even if I specified the call only when the array changes. Can someone tell me how to solve it? (I don't know if it's normal to happen or something that I need to be worried about)
Issue is useEffect
dependency [tweets]
:
so as per your code it will call useEffect
whenever there is a change in tweets
,
inside useEffect
you are updating it, so
useEffect --> setTweets --> useEffect --> setTweets --> ....
Solution:
useEffect(() => {
api.get('tweets').then(response => setTweets(response.data))
//}, [tweets]) // <--- remove tests from here
}, [])
As per the comment, you can do something like this:
unmounted is just for to not to get in error of "Can't perform a React state update on an unmounted component."
useEffect(() => {
let unmounted = false;
const timer = setInterval(() => {
api.get('tweets').then(response => {
// you can compare the current tweets with new also and update state only after that
if(!unmounted)
setTweets(response.data)
})
},5000)
return () => {
unmounted = true;
clearInterval(timer);
}
}, [])
Remove tweets
from the array of dependencies:
useEffect(() => {
api.get('tweets').then(response => setTweets(response.data))
}, [])
That array means, "whenever one of these values changes, re-run the function". So the function is getting run, getting new tweets, and then getting re-run because tweets
changes; that's the infinite loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.