0

I have a function that when I press a button I receive data [an array of objects]. I loop through this array to find one of the objects to store it in the state.

when I click the button the first time, the console log shows that the state was not updated, but when i click it again then it shows that the state was updated:

  constructor(props) {
    super(props);
    this.state = {
      listOfItems: [],
      isOpen: false,
      modal: null,
    }
  }
  findKey(key) {
    console.log(key);
    console.log(this.state.listOfItems);
    let foo;
    for (var i in this.state.listOfItems) {
      if (this.state.listOfItems[i].id == key) {
        foo = this.state.listOfItems[i];
        this.setState({ modal: foo });
      }
    }
 // the first time i call the func it returns null- the second time the obj
    console.log(this.state.modal)
  }

why is this happening?

thank you!

Baruch Karlin
  • 33
  • 1
  • 5
  • 2
    Does this answer your question? [Why calling setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately) – Brian Thompson Mar 11 '21 at 18:12

1 Answers1

0

The setState function in React is not mutating the this.state property, it actually waits for the execution of your function to finish and then triggers a re-render of the component (modify the state and call the render function again).

This means that in order to access your new values, you could use the render function, or you could you implement the componentDidUpdate function which accepts the old state as a second argument (right after the previous props argument) and can access the new state by using this.state.

This allows you to create a much more "Pure" code, which is why React implemented setState this way.