0

why the deck is not getting re-rendered when shuffeling happens on button click.Every time I click on shuffle button the deck is displayed as it is instead of shuffled one.

const Deck = () => {

    const [deck , newDeck] = useState(Card)
    return (
        <div>
        {console.log(deck)}
        <h2>Deck</h2>
        <Button type="button" onClick={() =>{newDeck(deck.sort(() => Math.random() - 0.5));}}>Shuffle</Button>
        {deck.map((card) => (
            <p key={Math.random()}>{card.value} of {card.type}</p>
        ))}
        
        </div>
    );
}
export default Deck;
underscore_d
  • 6,309
  • 3
  • 38
  • 64
Tina Shah
  • 19
  • 3
  • The reason it doesnt work is because you don't set the state to a new array. The value of deck is a reference to the array, and that dont change when you do like you do. You need to do this: `newDeck(prevValue => [...prevValue].sort(() => Math.random() - 0.5))` – hellogoodnight Apr 16 '21 at 14:57
  • I also recommend you to follow naming conventions. `const [deck , setDeck] = useState(Card)` – hellogoodnight Apr 16 '21 at 14:59
  • no problem, good luck – hellogoodnight Apr 16 '21 at 14:59

0 Answers0