0

I am stuck with a problem where I am updating React state with an array of objects where my original object is like this.

[{id:"123", name:"Product 1"}, {id:"456", name:"Product 2"}];

Suppose this is an e-commerce cart list, where now if I add the same product again, being 'id' property as unique for each product it should increase the quantity of that product.

I need this [[{id:"123", name:"Product 1 , quantity: 2"}, {id:"456", name:"Product 2"}];]

Instead I am getting state like this, [{id:"123", name:"Product 1"}, {id:"456", name:"Product 2"},{id:"123", name:"Product 1"} ];

I do not want that third item on my array, I want it to increase the quantity property which is also not available on the object before.

I am using React hooks on this

Please do help. Thanks in advance.

  • 1
    Can you show code how you are updating the state? – PsyGik Jul 06 '21 at 06:38
  • Does this answer your question? [How do I update states onchange in an array of object in React Hooks](https://stackoverflow.com/questions/55987953/how-do-i-update-states-onchange-in-an-array-of-object-in-react-hooks) – hakisan_ks Jul 06 '21 at 06:46
  • 1
    @PsyGik I have posted my code as an answer, somehow I managed to achieve my requirements. – Mohit Pandey Jul 06 '21 at 07:03
  • yes but you post a question. some of us tried to help you really quickly and you come back some minutes later posting your own answer? – Apostolos Jul 06 '21 at 07:04
  • @Apostolos Sorry if you get offended by this. I was stuck on this from long. And only after explaining my problem here I got more clarity on this. And yes I am really thankful for their quick replies, that's why I mentioned I got it working. – Mohit Pandey Jul 06 '21 at 07:09
  • ok please dont forget to accept an answer in order for the question to be considered "closed" and if an answer helped you solve your problem, you can upvote it too. regards – Apostolos Jul 06 '21 at 07:15
  • Excellent. This is the rubber duck debugging method. You explain the problem to someone else and find the solution! Good job! – PsyGik Jul 06 '21 at 10:31

3 Answers3

1

You need to find the index of the item inside the cart array based on the id and then update the quantity, or set it to 1 as initial value.

I added a small sample but you can adapt it to hooks code.

let cart = [{id:"123", name:"Product 1"}, {id:"456", name:"Product 2"}];
let newCart = JSON.parse(JSON.stringify(cart))
let index = newCart.findIndex(obj => obj.id === "123")

if (index >= 0) {
 newCart[index].quantity = (newCart[index].quantity | 0) + 1     
}

console.log(newCart)
Apostolos
  • 10,033
  • 5
  • 24
  • 39
1

I tried this after posting the question and it worked.

const addToCart = (productToAdd) => {
    const present = cartItem.some((prod) => {
      return prod.id === productToAdd.id;
    });
    if (!present) {
      productToAdd["quantity"] = 1;
      setcartItem((prev) => {
        return [...prev, productToAdd];
      });
    } else {
      setcartItem((prev) => {
        prev.map((prod) => {
          if (prod.id === productToAdd.id) {
            prod.quantity++;
          }
        });
        return [...prev];
      });
    }
  };
0

Use map() to iterate through existing state and update the object when id matches to the input.

const state = [
  { id: "123", name: "Product 1" },
  { id: "456", name: "Product 2" },
];

setState = (_state) =>
  state.map((item) =>
    item.id === _state.id
      ? { ...item, quantity: item["quantity"] + 1 || 2 }
      : item
  );

const newState = setState({ id: "123", name: "Product 1" });

console.log(newState);
PsyGik
  • 3,535
  • 1
  • 27
  • 44