Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Reload api data in setInterval in a fixed time period in react native

I am working on a React Native app where I am fetching data from an API. Now every day from 6 to 7 pm, I need to reload the API data in an interval time of 3 seconds as the data keeps changing in this period. I can't figure out how to do that. Here is the code I have right now:

async componentDidMount() {
  await fetch('https://api', {
    method: 'GET',
  })
  .then((response) => response.json())
  .then((response) => {
    this.setState({ tableData1: response.magnum })
    this.setState({ tableData2: response.special })
    this.setState({ tableData3: response.consolation })
    this.setState({ date: response.date })
    this.setState({ draw: response.draw })
  })
}

componentWillMount() {
  const { navigation } = this.props;
  this.focusListener = navigation.addListener("didFocus", () => {
    var today = new Date()
    var time = today.getHours()
    console.log(today.getMinutes())
    var weekDay = today.getDay()

  if ((time >= 18) && (time <= 19 )) {
    // I guess I need to do something here...
  }
});

I am confused if doing something in componentWillMount refresh the data again and again after every 3 seconds. Any help would be appreciated.

Upvotes: 1

Views: 1614

Answers (1)

fayeed
fayeed

Reputation: 2485

I would probably do something like this:

componentWillMount() {
  const { navigation } = this.props;
  this.focusListener = navigation.addListener("didFocus", () => {
    var today = new Date()
    var time = today.getHours()
    console.log(today.getMinutes())
    var weekDay = today.getDay()

  if ((time >= 18) && (time < 19 )) {
    var setIntervalId = setInterval(() {
      // make api call;
    }, 300);

    var min = 60 - today.getMinutes();
    var mili = min * 60000;

    setTimeout(() => clearInterval(setIntervalId), mili);
  }
});

Let' say you start the making API calls at 6:21 so you would want to keep making API calls for remaining 39 minutes that's the min variable and since the setTimeout function accepts a duration value in milliseconds so I just converted it to milliseconds.

Upvotes: 2

Related Questions