Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first item of array in react state

I know how to do this but trying this way and not sure why it wont work?

  drawCard = () => {
    const deck = this.state.cards;
    deck.shift();
    console.log(deck, 'deck'); //this is correctly logging one less everytime
    this.setState({cards: deck})
  }

cards is just an of objects

so even though the function is being called and the console log is working, why is it not updating state?

(console.log(state.cards.length) always returns 3)

like image 546
The Walrus Avatar asked May 03 '18 18:05

The Walrus


People also ask

How do I remove the first index of an array in React?

shift() The shift() method removes the first element from an array and returns that removed element.

How do I remove element from state array React?

To remove an object from a state array in React: Use the filter() method to iterate over the array. On each iteration, check if a condition is met. Set the state to the new array that the filter method returned.

How do you remove the first data from an array?

The shift() method removes the first item of an array. The shift() method changes the original array.


1 Answers

Don't use methods that mutate the state (for instance, Array#shift). You could instead use Array#slice to return a shallow copy of a portion of the array:

drawCard = () => {
  this.setState({ cards: this.state.cards.slice(1) })
}
like image 155
djfdev Avatar answered Oct 16 '22 08:10

djfdev