8

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)

1
  • 3
    You are mutating the state. Try const deck = [...this.state.cards]; Commented May 3, 2018 at 18:30

3 Answers 3

14

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

3 Comments

ok it is when i log it in the function but not when i log the state in render?!
Perhaps you should share the full code of your component.
yeh i had a mare, sorry. sorted now :D
-1

The problem arises because you are directly modifying the state. Although you are assigning the state to 'deck' remember that in Javascript arrays and objects are references. So when you are modifying deck you are actually trying to modify the state itself. You can use other methods to create a copy of the states values and modify that.

You may find this helpful: React - Changing the state without using setState: Must avoid it?

Comments

-2

in react, you can't just change the state, you need to create a copy of your state before updating,

the easiest way to do it is just replace this:

 const deck = this.state.cards;

into this:

const deck = [...this.state.cards];

1 Comment

i guess you new in reactjs, you better check out the react state approach (medium.freecodecamp.org/…) (good article about that). any way, you don't change the value of the state, you should get a copy of the data, then change the copy and finally use the setState function, that would update your state

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.