Akil Hylton
Akil Hylton

Reputation: 21

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

Upvotes: 2

Views: 6429

Answers (1)

xs0
xs0

Reputation: 2897

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(...);
}

Upvotes: 9

Related Questions