0

I have the following function, lists=[] at start:

handleAddList(s) {

   var temp = this.state.lists.slice();
   temp.push(s);
   console.log(temp);
   this.setState({lists: temp},console.log(this.state.lists) ); 
}

why does the first console.log return the value of s but the second console.log returns []?

also, why if i remove slice() do both console.logs now show the value of s?

kind user
  • 40,029
  • 7
  • 67
  • 77
DCR
  • 14,737
  • 12
  • 52
  • 115

1 Answers1

1

The second console log returns [] because it hasn't been set yet because calls to setState are async.

When you remove .slice() you are creating a reference to this.state.lists and mutating it directly which is not async so it happens immediately. However, mutating state directly should never be done.

Instead, keep using .slice() to clone your state, then mutate the clone and setState as needed. When you need to view state you should use react-devtools.

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65