React nested state object not updating

564 Views Asked by At

I am trying to update a nested state object (checkedObjects) in a react class component, to track when checkboxes are checked and unchecked. checkedObjects has the following structure:

checkedObjects: {
[assignmentName]: boolean,
}

verifyObjects is a local variable that checks if the new name property was actually received. When I console out the contents of these objects however, checkedObjects is empty, while the new property was added to verifyObjects (see screenshot below). Can anyone advise why the state variable checkedObjects is not updating immediately?

Screenshot:

enter image description here

Code Snippet:

this.state = {
    checkedObjects: {},
};

incrementCount(totalCount, id, checked, assignmentName) {
     console.log("increment: totalCount", totalCount, " ; id:", id, checked);
     // If a checkbox is clicked with an assignment name store on the checkedObjects
     if (assignmentName) {
       let verifyObjects = { ...this.state.checkedObjects };
       verifyObjects[assignmentName] = checked;
   
       this.setState(prevState => { 
         let tempObj = {...prevState.checkedObjects}
         tempObj[assignmentName] = checked;
         return {checkedObjects: tempObj}
       });
   
       console.log("SelectedAssignmentsObj:", this.state.checkedObjects);
       console.log("VerifiedObject:", verifyObjects);
     } //if
   }
1

There are 1 best solutions below

0
On

State updates don't occur instantaneously. When we call the setState() function, it schedules a state update. Try console logging tempObj to see the value that is being put inside of this.state.checkedObjects.

In short, your code is working the way it should but you wont be able to see the state update right after calling this.setState() [because the state update is scheduled and didnt happen at that instant]. If you want to ensure that your state did update the way you wanted, can add a dummy button on the side that console logs the value of this.state.checkedObjects or you can use the chrome extension React Developer Tools to find out the values in the state object.