3

I'm trying to implement some api polling code, this is what I've got so far:

async retrieveNotifications() {
  const res = await fetch(url)
  if (res.status === 200) {
    this.props.setNotifications(res.data)
  }
  setTimeout(() => {
    this.retrieveNotifications()
    // polling in 10 min cycles
  }, 600000);
}

the code works, however the question is if this has any performance downsides because its recursive? Does anyone know a better solution for polling in rn ? Thanks for the help :)

Konstantin Paulus
  • 1,943
  • 2
  • 10
  • 22

2 Answers2

2

Not sure about the performance implications of recursion here (or even if a setTimeout closure counts as recursion exactly), but you could use setInterval to call a polling method every 10 minutes, without needing to daisy-chain the calls. And don't forget to use clearInterval when you want it to stop!

For example:

async retrieveNotifications() {
    const res = await fetch(url)
    if (res.status === 200) {
        this.props.setNotifications(res.data)
    }
}

//inside some class method
setInterval(this.retrieveNotifications, 600000);
bmovement
  • 827
  • 7
  • 11
  • Is there an easy way this works with async await ? I don't like working with promises ^^ – Konstantin Paulus Apr 22 '19 at 19:59
  • I think it will just work... the async/await pertains to what happens inside your method. The interval won't wait on it, but the code inside your method should behave like before. Example added above. – bmovement Apr 22 '19 at 20:07
  • I really appreciate your help guy, your code almost worked, it somehow returned undefined as res.data like this, I had to make a fat arrow function out of retrieveNotifications for it to work, ill post the working code for anyone running into the same problem, it looks much better as you suggested – Konstantin Paulus Apr 22 '19 at 20:35
  • Study this for detailed usage of setInterval() clearInterval(). React Hooks will be much more optimised. https://overreacted.io/making-setinterval-declarative-with-react-hooks/ – Sikandar Khan Feb 17 '21 at 13:30
0

This is the improved code as suggested form @bmovement, thanks for your help :D

constructor() {
  super()
  // polling in 10 min cycles
  this.interval = setInterval(this.retrieveNotifications, 600000)
}

componentDidMount() {
  this.retrieveNotifications()
}

componentWillUnmount() {
  clearInterval(this.interval);
}

retrieveNotifications = async () => {
  const res = await fetch(url)
  if (res.status === 200) {
    this.props.setNotifications(res.data)
  }
}
Konstantin Paulus
  • 1,943
  • 2
  • 10
  • 22