Reputation: 21
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
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