4

I'm trying to set a state from a fetch response, but it seems it takes a while to update the state.

What I learned is that fetch is quick until it comes to setState. There, it takes about 3 seconds to update.

fetch(ENDPOINT)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({product : responseJson.product, related: responseJson.related, ready: true});
      })
      .catch((error) => {
        console.error(error);
    }).done();

Any tips?

Thanks

suman j
  • 6,710
  • 11
  • 58
  • 109
Lucas Veiga
  • 1,758
  • 7
  • 27
  • 45

1 Answers1

7

setState is asynchronous.

From the docs of react itself if you see :-

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

You can read more about this in the documentation.

Also, you can check something similar here

Community
  • 1
  • 1
Harkirat Saluja
  • 7,768
  • 5
  • 47
  • 73