1

I use number useParams to get a number from a URL path and deck array to get data from data array which contains 32 objects with id and src (URL for image) properties.

// Images.js

const data = [
    {
        id:1,
        src:'https://###.com/###',
    },
    //...

const Images = () => {
    const {number} = useParams()
    const [deck, setDeck] = useState(data);
    //...

Then I use useEffect to fetch number from URL path and setCards() function to display proper amount of cards based on a given number from the URL by deleting indexes from number to deck.length. shuffle() function does not matter here it just places objects in a random order.

// Images.js

useEffect(() => {
  fetch(`http://localhost:3000/play/${number}`).then(setCards(number));
}, [number]);

const setCards = (number) => {
  let tempDeck = deck;
  tempDeck.splice(number, deck.length);
  shuffle(tempDeck);
  setDeck(tempDeck);
};

I also use this piece of code to render the proper amount of cards from the web page by routing to the proper URL path:

// Home.js

<div className="btn-group">
  <Link to="/play/8">
    <button className="btn">8 cards</button>
  </Link>
  <Link to="/play/16">
    <button className="btn">16 cards</button>
  </Link>
  <Link to="/play/24">
    <button className="btn">24 cards</button>
  </Link>
  <Link to="/play/32">
    <button className="btn">32 cards</button>
  </Link>
</div>;

Whenever I make an initial render and for example select "24 cards" button everything is fine, 24 out of 32 cards are displayed as should be, but when I come back to the "main page" and select a higher value of cards in this case it would be 32 from "32 cards" button, browser will display only 24 cards instead of 32. How can I fix it?

3
  • 1
    try with let tempDeck = [...deck] in setCards function; Commented Nov 2, 2021 at 14:19
  • @FrancescoClementi funziona, grazie! Commented Nov 2, 2021 at 14:23
  • daje! scrivo una risposta più argomentata per gli altri così puoi accettarla Commented Nov 2, 2021 at 14:25

1 Answer 1

1

With this code:

let tempDeck = deck;
tempDeck.splice(number, deck.length);

you are editing your original array.

You should consider to create a shallow copy of your original array and edit it:

let tempDeck = [...deck];
tempDeck.splice(number, deck.length);
Sign up to request clarification or add additional context in comments.

Comments

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.