2

Excuse me for the rookie question, I'm new in react.
I have multiple components in some of which I make Api calls in interval to keep the list up to date.

In Angular, I could create a service broadcasting an event in intervals using requestAnimationFrame and make Api calls in those events. This is a good idea because:

  • We're not creating many intervals in many components, staying DRY.
  • We're reducing the risk of non-destroyed intervals.
  • We're saving Api calls when application is not in active tab.
  • We can manipulate the rate of Api call in a single service.

and some other advantages.

In many cases like this I read it's not a good approach to do the same in react/redux and we better try keeping action dispatches to a minimum. but if I creat an interval in every component it's not DRY anymore.

My question is which one of these ways I should choose or is there another approach?

Reyraa
  • 4,174
  • 2
  • 28
  • 54
  • Does every subsequent request need to cancel the previous request? – james emanon Jun 10 '17 at 18:53
  • @jamesemanon I call one endpoint at a component and that's every 10s. Practically no. – Reyraa Jun 10 '17 at 18:55
  • The answered you linked is pretty much how would I handle it too. Action dispatching is very cheap in Redux it's absolutely fine to trigger them as often as you want (the performance catch is store updating but not an issue here). Keep a particular timer in a manageable component makes the developer super easy to track the life cycle of the timer. – yujingz Jun 13 '17 at 17:37

1 Answers1

1

You can use reacts componentDidMount() which is very simple for setting one time interval and making an api call although it is not much recommended but you can use it for test purpose take for example.

componentDidMount() {
    this.myInterval = setInterval(() => {

        const { seconds} = this.state

        if ( seconds> 0 ) {
            this.setState(({ seconds }) => ({
                seconds: seconds -1
            }))
        } else if (seconds==0) {
            return(this.color('#840000'))
        }
    }, 1000) 
    Axios.get('https://jsonplaceholder.typicode.com/users')
  .then(response => {
      console.log(response);
      this.setState({ items: response.data.result.items});
  })
  .catch(error => {
    console.log(error);
  });
}
Abdul Rauf
  • 90
  • 2
  • 14
  • 1
    We should just clear the interval in `componentWillUnmount`. or using hooks with the returned function of the `useEffect`. – Reyraa Jan 15 '20 at 19:13