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;
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)) Commented Apr 16, 2021 at 14:57
  • I also recommend you to follow naming conventions. const [deck , setDeck] = useState(Card) Commented Apr 16, 2021 at 14:59
  • no problem, good luck Commented Apr 16, 2021 at 14:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.