1

Please help me to find a solution and a bit with my code refactoring.

I just want to put some objects from one array to a new and it will be like a product cart. That's why I don't want to see any duplicates but just: product - quantity in the modal window. I've got two arrays:

state = {
  existData: [
    {
      productName: "CoolProductName 1",
      count: 0,
      image: "src.jpeg",
      author: "Name Surname",
      date: "21.02.2020",
      id: 1,
    },
    {
      productName: `CoolProductName 2"`,
      count: 0,
      image: "src.png",
      author: "Name Surname",
      date: "21.02.2020",
      id: 2,
    },
  ],
  addedToCart: [],
};

So, the function is:

added = (id) => {
  //get product Id from other component

  this.setState(({ addedToCart, existData }) => {
    let newObj = existData.filter((el) => el.id === id); // there is I get product selected by user from array of all products

    return {
      addedToCart: [...addedToCart, ...newObj],
    };
  });
};

With my little knowledge I thought to do something like:

let newObj = existData
  .filter((el) => el.id === id)
  .map((el) => {
    if (el.count >= 0) {
      el.count++;
    }
    return { ...el };
  });

yes it returns value with the count++ but in addedToCart array I've got duplicates objects with different counts. I see two ways:

  1. remove duplicates in addedToCart array after add an object to the cart and increase count then just show something like {addedToCart.prductName} - {addedToCart.count} in the cart.
  2. count duplicate objects and remove count field.

What is the better way and suitable code? Thank you

1
  • There is solution suitable to me: ` added = (id) => { this.setState (( { addedToCart, dataList } )=>{ // filter return an Array but // find return an element, what we are looking for by id const newItem = dataList.find(el=>el.id===id); const mainArr = [...addedToCart ]; // if there is no in shopping cart if(mainArr.find(el=>el.id===id) == undefined){ newItem.count = 1; mainArr.push(newItem); } // if exist then count ++ else{ mainArr.find(el=>el.id===id).count++; } return{ addedToCart: mainArr } })}; ` Commented Apr 22, 2021 at 14:49

2 Answers 2

2

I would keep aside count from product Details. Also, addedToCart would be an object, where its key are the ids with and the value is the count;

new state format:

state = {
  existData: [
    {
      productName: "CoolProductName 1",
      image: "src.jpeg",
      author: "Name Surname",
      date: "21.02.2020",
      id: 1,
    },
    {
      productName: `CoolProductName 2"`,
      image: "src.png",
      author: "Name Surname",
      date: "21.02.2020",
      id: 2,
    },
  ],
  addedToCart: {}, //store id and count here
};

this way added would check for id keys to update its count:

added = (id) => {
  //get product Id from other component
  this.setState(({ addedToCart }) => {
    const count = typeof addedToCart[id] === "undefined" ? 1 : ++addedToCart[id];
    return { addedToCart: { ...addedToCart, [id]: count } };
  });
};

This way you avoid any object duplication, and segregates cart's items from product details. If you need to access a product's count you can check this.state.addedToCart[id] if it exists and return its count accordingly.

basic implementation example:

cart-example

Sign up to request clarification or add additional context in comments.

Comments

0

According to React docs, setState should be like: setState(updater, [callback]),

If I'm not mistaken, your are passing a callback in the place of the updater.

It should look like this.setState({ state: 'something' }, () => { console.log('something') })

React does not accept calling new functions with pre existents Components names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.