Reputation: 115
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?
Upvotes: 1
Views: 47
Reputation: 2092
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);
Upvotes: 1