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!