Find the corresponding ID in the array and increase the value of the element

To increment the productQuantity of an item that has been added to an array, I am implementing a logic where if the productID of the item matches an existing item in the array, then the quantity should be increased.

export function ADD_ITEM(state, product) {
    // state.isAdded = true;
    const added = state.storeCart.find(item => item === product.productID);
    if (!added) {
        state.storeCart.push(product);
    } else {
        product.productQuantity++;
    }

Answer №1

It appears that there are a couple of issues that need to be addressed.

  1. The product parameter in your find callback function is overshadowing the product parameter from the ADD_ITEM function. To avoid confusion, let's rename it to p.
  2. Within the find callback, you need to verify if the productID of p matches the provided product's ID.
  3. It seems like you intend to simply add the entire product object to the storeCart, rather than pushing each individual property separately.
  4. Be sure to increment the productQuantity property on added, as it references the existing item in the state.
export function ADD_ITEM(state, product) {
  const added = state.storeCart.find(p => p.productID === product.productID);
  if (!added) {
    state.storeCart.push(product);
  } else {
    added.productQuantity++;
  }
}

To illustrate the functionality of this code, here is a basic example:

function ADD_ITEM(state, product) {
  const added = state.storeCart.find(p => p.productID === product.productID);
  if (!added) {
    state.storeCart.push({...product});
  } else {
    added.productQuantity++;
  }
}

const state = {
  storeCart: []
}

const hat = { productID: 1, name: "hat", productQuantity: 1 };
const jacket = { productID: 2, name: "jacket", productQuantity: 1 };
const shoes = { productID: 3, name: "shoes", productQuantity: 1 };

ADD_ITEM(state, hat);
ADD_ITEM(state, jacket);
ADD_ITEM(state, shoes);
ADD_ITEM(state, jacket);

console.log(state);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a duplicate of an object in Vue.js by utilizing the script tag or storing it inside the instance,

Curious about the best practice for handling this code and understanding the difference between cloning an object inside a script tag versus doing it in a data property: <script> import {cloneDeep} from "lodash"; import {INVITE_USER_FORM_FIELDS} ...

I am experiencing issues with using props data in the componentDidMount method in react-native

I have been grappling with this issue for the past day. The challenge lies in passing props from my parent class and accessing the data in my child component. While the data displays correctly when rendered, it appears as null when called in componentDidMo ...

What is the proper way to implement Firebase getDoc in Vue with vue-concurrency?

I am currently in the process of developing a TypeScript Vue composable that utilizes Firebase and the vue-concurrency library. According to the documentation, I need to explicitly type any intermediate values that are yielded. I am facing a challenge wh ...

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...

Issue in d3.js: bisector consistently returning zero

http://jsfiddle.net/rdpt5e30/1/ const data = [ {'year': 2005, 'value': 771900}, {'year': 2006, 'value': 771500}, {'year': 2007, 'value': 770500}, {'year': 2008, 'value&apos ...

Explaining how to iterate through objects (one by one) in the This.questionnaire.Profile at every click using JavaScript (answer not found in forums)

Creating a series of questions, each part being stored in This.question = {p1: {...}, p2: {...}, p3: {...}, p4: {...}, p5: {...} etc. (and many more). I want to be able to switch from one article to the next every time I click a button... click => next ...

Achieving consistent outcomes across various devices: What's the secret?

Hey there, I am facing an issue with my form page that I created using HTML, CSS, and Javascript. It looks good on my computer but appears messy on a mobile phone. The elements are getting out of the white box (div) making the entire page look chaotic. Sin ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

Show validation message using Bootstrap near the submit button

My form consists of around 40 questions, some required and some optional. Upon clicking "submit," I utilize Bootstrap's form-validation.js to verify the form before submission, which works seamlessly. However, due to the length of the form, when a us ...

Displaying content based on changing conditions fetched from the database

We are currently developing a dynamic form system where users can create custom questions in the admin panel and set conditions to display them based on the values of other questions. ng-show="((UserCode==10003 && Name=='Ankur') ||(State ...

An alternative to passing AngularJS expressions to PHP or Ajax

Within my PHP/HTML file, I have an AngularJS expression that looks like this: {{data.po_id}} This expression is included as <td>{{data.po_id}}</td> within a table row. I am trying to use this expression as a parameter for a PHP function in t ...

Ways to define two ng-change functions simultaneously

I am currently working on implementing the phonechange and emailchange functions simultaneously. My goal is to trigger an alert message when both the phone number and email entered are valid. Any assistance from you all would be greatly appreciated! $sc ...

The Highcharts Range Selector feature may encounter issues when used with multiple series

Currently, I am facing an issue with my highchart/highstock where I retrieve data from a PHP file. The problem arises when I attempt to use multiple series as the RangeSelector Buttons cease to function properly. For instance, in the example provided, the ...

Why can my JavaScript server code read "2011" but not "20,11" when both are formatted as strings?

Currently, I am trying to establish a connection between Storm and JavaScript through redis. While the redis aspect of the connection is functioning correctly, I am encountering an issue when attempting to publish tuples (essentially Strings). Even though ...

Is it possible to load Angular.js without any references?

In the process of reverse engineering a User Interface that is operational but has a few bugs. Created using HTML, CSS, and JavaScript with data acquired through a REST API. The interface is designed for a Windows environment. While examining the index.ht ...

Tips for using conditional rendering with React and TypeScript

Issue with Conditional Rendering in TypeScript It seems like I might have encountered a problem with the way I declare my components. Take a look at this TypeScript snippet: import React, { FunctionComponent } from 'react'; export const Chapte ...

Unable to close Bootstrap 5 modal

All of my modal forms are functioning properly, except for one that I migrated from Bootstrap 4 to Bootstrap 5. This particular modal refuses to close. Neither the Close button (the X at the top of the popup) nor the Cancel button will close the modal. I ...

When adding a new div, ensure it is counted and delete it once a new div is added

When clicked, a new div is added. When clicked again, another div with the same content is created as a duplicate. Q: Is there a way to remove the previous div when a new one is created? $(document).on('click', '.LibSectOpen', functio ...

What is the best way to arrange two objects depending on the frequency of elements in an array field?

Imagine having two objects, each containing two array fields: const list1 = { name: 'list-1', fruits: ['banana', 'strawberry', 'cherry'], vegs: ['lettuce', 'avocado', 'beans'] }; ...

Swap out the <a> tag for an <input type="button"> element that includes a "download" property

I have been working on a simple canvas-to-image exporter. You can find it here. Currently, it only works with the following code: <a id="download" download="CanvasDemo.png">Download as image</a> However, I would like to use something like th ...