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)
shift() The shift() method removes the first element from an array and returns that removed element.
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.
The shift() method removes the first item of an array. The shift() method changes the original array.
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) })
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With