0

React newbie here, so please be kind. I've got an object called results which is a fairly large object, containing a number of smaller objects. I've been able to ascertain that it's coming through in the componentDidMount() hook, but after going through the code in the hook, I've come to find that the population of a separate state object to the same value of results isn't working.

  state = {
    homeDesignNameText: "",
    resultsPrime: {}
  };

  componentDidMount() {
    const {
      results,
    } = this.props;

    console.log(">>MNTR", results);

    if (results &&
      results.status !== 404 &&
      results.items &&
      results.items.length) {

        console.log(">>BEEP");

      if(!this.state.resultsPrime.items) {
        console.log(">>BOOP");

        this.setState({
          resultsPrime: {...results}
        });
        console.log(">>BEEP2", this.state.resultsPrime);
      }
    }
  }

When I run the page containing these, I do get >>MNTR coming through in console.log() with the value of the results object. I then get >>BEEP and >>BOOP come through but once >>BEEP2 comes through in console, the only thing that comes out is {}.

One would assume that if >>BOOP is reached that the this.setState() call is also made, but it doesn't appear to be the case. What exactly am I doing wrong and how do I fix this to ensure that this.state.resultsPrime also contains the value of results?

Eliseo D'Annunzio
  • 592
  • 1
  • 10
  • 26
  • You should check docs about "setstate callback" to understand state – Ryan Nghiem Jun 28 '21 at 07:24
  • Setstate operation is asynchronous https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync#:~:text=Yes%2C%20setState()%20is%20asynchronous.&text=React%20does%20not%20guarantee%20that,command%20to%20update%20the%20component. – Ashish Bairwa Jun 28 '21 at 07:30

1 Answers1

2

The updated state isn't being consoled because state changes are asynchronous . To get the updated state you can log it using a callback as:

  this.setState({
          resultsPrime: {...results}
        },()=> console.log(">>BEEP2", this.state.resultsPrime));

Here the console.log will be executed only once the resultsPrime state got updated. You can read more about state change callbacks here

NeERAJ TK
  • 2,447
  • 1
  • 11
  • 25