1

I pushed an element to an array in a function( event), after pushing this element to the array I am getting this error,

handleAddList(s) {
  this.setState({lists :this.state.lists.push(s) });
  console.log(this.state.lists);
}

lists.map is not a function. list a react component

if I write it as this

handleAddList(s) {
  this.setState({lists :['something','something else']});
  console.log(this.state.lists);
}

But when I define lists manually it works well. Just when I push a new element in the array I get this error. Also if push destroys the array. Best regards

Harsha pps
  • 1,769
  • 2
  • 23
  • 34
mojtaba1
  • 53
  • 9

2 Answers2

1

The result of push is the length of the array, which is not what you want. You want to create a new array with the new object in it instead:

handleAddList(s) {
  this.setState(
    previousState => {
      return { lists: [...previousState.lists, s] };
    },
    () => {
      console.log(this.state);
    }
  );
}
Tholle
  • 97,067
  • 19
  • 174
  • 171
0

push returns the length of the array after appending the element and not an array, what you need is concat

handleAddList(s) {
    this.setState({lists :this.state.lists.concat([s]) });
}

Also setState doesn't update the state immediately You would need to use callback like

handleAddList(s) {
    this.setState({lists :this.state.lists.concat([s]) }, () => { console.log(this.state.lists)});
}
Shubham Khatri
  • 246,420
  • 52
  • 367
  • 373