Shota Donguzashvili
Shota Donguzashvili

Reputation: 43

React calls API every time user updates state and keeps old api alive

i have issue when page loads it calls api one time, after user changes date it calls api again to change data to that date but it keeps old api alive and adding new one also, with this page gets very slow,

this is api when page loads

this is api when page loads

this is api when date updated two time

enter image description here

this is code when i call api on page load

  componentDidMount() {
    this.fetchData(this.state.startDate, this.state.endDate);

  }

this is code every time i update api

 updateDate = (start, end) => {
      this.setState({startDate: start})
      this.setState({endDate: end})
      this.fetchData(this.state.startDate.startDate, this.state.endDate.endDate);
  }

Upvotes: 0

Views: 581

Answers (2)

Ankit
Ankit

Reputation: 9

Correct way is to use this.setState({object}, callBack after state is changed)

this.setState({startDate: start, endDate: end}, this.fetchDate(startDate,endDate))

You need to club these two lines to one .

this.setState({startDate: start})
this.setState({endDate: end}) 

to

this.setState({startDate: start, endDate: end})

Upvotes: -1

Ryan Le
Ryan Le

Reputation: 8422

What you are seeing at the network tab is a list of history fetch that you called

This means that they are not all alive but rather history records, it's only alive in your term if they are having status pending.

You would need to check for a performance issue somewhere else, such as server response time or re-rendering of components.


Here is a pending status:

A pending status

Upvotes: 4

Related Questions