Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Polling

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 :)

like image 669
Kape Avatar asked Oct 14 '25 03:10

Kape


1 Answers

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);
like image 103
bmovement Avatar answered Oct 17 '25 16:10

bmovement



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!