Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

326
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!