Omar
Omar

Reputation: 3411

what component lifecycle would you use to update data received from an api

state={url:'someurl' , stockData=[], error:false}

On initial mount i will grab the data from api and set it to state.

      componentDidMount() {
        this.getDataFromApi();
      }

Function for grabbing the data and setting the state of stockData

    getDataFromApi = () => {
        fetch(this.state.url)
          .then(res => res.json())
          .then(
            res => {
              const sortedRes = res["results"].sort(function(a, b) {
                return b.ask_price - b.bid_price - (a.ask_price - a.bid_price);
              });
              this.setState(
                {
                  stockData: sortedRes
                }
              );
            },
            res => this.setState({ error: true })
          );
      };

This data is always changing how can I get real-time updates?

I tried using componentWillUpdate to compare current and next state and using setTimeOut with delay of 3 seconds so that it was not calling fetchData() so quickly but the delay was not working and fetchData was being called way too many times in a short amount of time.

  componentWillUpdate(nextProps, nextState) {
 if(nextState.stockData !== this.state.stockData) {
    fetch(this.state.url)
      .then(res => res.json())
      .then(this.delay(function() {
              res => {
                const sortedRes = res["results"].sort(function(a, b) {
                  return b.ask_price - b.bid_price - (a.ask_price - a.bid_price);
                });
                console.log(sortedRes);
                this.setState(
                  {
                    stockData: sortedRes
                  },
                //  () => console.log("SORTED RES", sortedRes)
                );
              },
              res => this.setState({ error: true })
      }, 3000)) // waits 3s
      return true;
    }
    else {
      return false;
    }
  }

Upvotes: 0

Views: 46

Answers (1)

Andrew
Andrew

Reputation: 7545

The reason why setTimeout isn't working is because you aren't stopping each call from occurring. You're just delaying each one by 3 seconds. I suggest placing the entire Api call inside a setInterval in componentDidMount.

componentDidMount() {
  this.apiCall = setInterval(() => {
    this.getDataFromApi();
  }, 3000)
}

Remember to do housekeeping when the component unmounts as well, or else your setTimeout will never stop, even when the component is removed from the DOM.

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

Upvotes: 1

Related Questions