0

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)

2 Answers 2

1

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);
    }
}, []) 
Sign up to request clarification or add additional context in comments.

8 Comments

but if I make this, the request will happen only when the component mounts, and I won't be able to see the new post unless I refresh the page, and I don't want this to happen
@GabrielTisoVinhasdeBrito,so when do you want new posts?
when the user submits a new one
do you have a suggestion/
I don't know if it's normal, but I keep getting GET requests when I check Network (in a much slower rate, that's good). Is it normal, or I have to implement another functionality in your code?
|
0

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.

1 Comment

if I remove the tweets, I'll have to refresh the page to see the new post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.