Home > Software engineering >  How to update a state using nextjs? [duplicate]
How to update a state using nextjs? [duplicate]

Time:09-21

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!

CodePudding user response:

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.

  • Related