showing results for - "react refresh api call"
Ange
01 Aug 2020
1  
2    import React, { Component } from 'react';
3
4    class Dashboard extends Component {
5      /*
6        declare a member variable to hold the interval ID
7        that we can reference later.
8      */
9      intervalID;
10
11      componentDidMount() {
12        /*
13          need to make the initial call to getData() to populate
14         data right away
15        */
16        this.getData();
17
18        /*
19          Now we need to make it run at a specified interval,
20          bind the getData() call to `this`, and keep a reference
21          to the invterval so we can clear it later.
22        */
23        this.intervalID = setInterval(this.getData.bind(this), 5000);
24      }
25
26      componentWillUnmount() {
27        /*
28          stop getData() from continuing to run even
29          after unmounting this component
30        */
31        clearInterval(this.intervalID);
32      }
33
34      getData = () => {
35        // do something to fetch data from a remote API.
36      }
37
38      render() {
39        return (
40          <div>
41            Our fancy dashboard lives here.
42          </div>
43        );
44      }
45    }
46  
47
Monica
09 May 2018
1  
2    import React, { Component } from 'react';
3
4    class Dashboard extends Component {
5      intervalID;
6
7      state = {
8        data: [],
9      }
10
11      componentDidMount() {
12        this.getData();
13      }
14
15      componentWillUnmount() {
16        /*
17          stop getData() from continuing to run even
18          after unmounting this component. Notice we are calling
19          'clearTimeout()` here rather than `clearInterval()` as
20          in the previous example.
21        */
22        clearTimeout(this.intervalID);
23      }
24
25      getData = () => {
26        fetch('/endpoint')
27          .then(response => response.json())
28          .then(data => {
29            this.setState({ data: [...data] });
30            // call getData() again in 5 seconds
31            this.intervalID = setTimeout(this.getData.bind(this), 5000);
32          });
33      }
34
35      render() {
36        return (
37          <div>
38            Our fancy dashboard lives here.
39          </div>
40        );
41      }
42    }
43  
44