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

328
Visualizações
How to update a state using nextjs?

I have been working on a next.js project, and I have a part that acts as a shopping cart. When you click on an item, it adds the item image to a list and renders all the selected items. To remove the item, you can click on the small icon. When the small icon is clicked, I splice that list and update the prop, but it doesn't update until adding another item. I have seen this question, but when I implement it, it gives an error. I have also read this article, but it also doesn't like that. I have also posted my project on code on code sandbox here.

var cartImages = [];
export default function Home({ data }) {
    const removeitem = (index) => {
        cartImages.splice(index, 1);
        setCartImg(cartImages);
    };
    const [cartImg, setCartImg] = useState(cartImages);
    return (
    <Popup onClick={removeitem} />);
}

Thanks for you're time!

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

0

You codesandbox is updated. Please review. I've commented some of the code. Basically, there were two issues.

  1. Total was not updating on the item removal, because the total was not being updated after item removal.
  2. CartImg state was not being reflecting the change on removal.

to solve the first issue, I updated the removeItem function to use and update the state variable cartImg.

const removeitem = (index) => {
  console.log(index);
  const updated = cartImg.filter((item, idx) => idx !== index); // remove the item based on the index property
  if (!updated.length) setPopup(false);
  setCartImg(updated);
};

also updated the total prop in the Popup component

total={cartImg.reduce((partial_sum, a) => partial_sum + a.price, 0)}

To solve both issues, I updated the cartImg state to store the url and price of a item in the object. Than sum the total of the items in the cartImg array.

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