Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
Problem with manipulating data in array, react

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda