最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React JS setInterval to API - Stack Overflow

programmeradmin0浏览0评论

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

ponentDidMount() {
  fetch(fullURL)
    .then((response) => response.json())
    .then((responseJson) => {
      // console.log(responseJson);
      const resultyt = responseJson.items.map(obj => "/" + obj.id.videoId);
      this.setState({resultyt});
    })
    .catch((error) => {
      console.error(error);
    });
}

the API call is stored inside a const called fullURL

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

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

the API call is stored inside a const called fullURL

Share Improve this question edited Nov 19, 2017 at 17:24 linasmnew 3,9772 gold badges22 silver badges33 bronze badges asked Nov 19, 2017 at 16:40 Akil HyltonAkil Hylton 211 silver badge6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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

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

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

loadData() {
    fetch(fullURL).then(...);
}
发布评论

评论列表(0)

  1. 暂无评论