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

1
  • Using concat instead of push would do the trick Commented Jul 30, 2018 at 13:09

2 Answers 2

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);
    }
  );
}
Sign up to request clarification or add additional context in comments.

Comments

1

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)});
}

2 Comments

thank you very much my dear friend. that was a great help. thanks
@mojtaba1 Glad to have helped :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.