Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

327
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda