Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS setInterval to API

I want to make a call to an API once an hour, every hour, using setInterval, how would I go about implementing that?

componentDidMount() {
  fetch(fullURL)
    .then((response) => response.json())
    .then((responseJson) => {
      // console.log(responseJson);
      const resultyt = responseJson.items.map(obj => "https://www.youtube.com/embed/" + obj.id.videoId);
      this.setState({resultyt});
    })
    .catch((error) => {
      console.error(error);
    });
}

the API call is stored inside a const called fullURL

like image 921
Akil Hylton Avatar asked Feb 14 '26 23:02

Akil Hylton


1 Answers

Wrap that up in a function that can be called many times, then simply use setInterval:

componentDidMount() {
    this.intervalId = setInterval(() => this.loadData(), 3600000);
    this.loadData(); // also load one immediately
}

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

loadData() {
    fetch(fullURL).then(...);
}
like image 76
xs0 Avatar answered Feb 16 '26 11:02

xs0



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!