score:2
Accepted answer
includes
will not work with objects. try find
or findIndex
instead.
Also I think your check is wrong. You need to check if items
has the selected productId
and if yes, then update its count.
const addCart = (productsId) => {
setCount(count + 1)
data.forEach((product) => {
let index = items.findIndex(itm => itm.id === product.id && productId === product.id)
if (index >= 0) {
let newProduct = { ...items[index] }
newProduct.count += 1
setItem( [...item, [index]: newProduct ])
} else {
setItem(item.concat(product))
}
})
}
score:0
Since product is an object, includes
will not work as it only do "shallow" comparison like if you have a simple array (i.e ['a', 'b', 'c'].includes('c');
In your case you need to "find" the product by id to know if it exist.
const addCart = (productsId) => {
setCount(count + 1)
data.forEach((product) => {
const exist = item.find(i => i.id === product.id); // add this one
if (exist) {
product.count += 1
} else if (product.id === productsId) {
setItem(item.concat(product))
}
})
}
You can learn more about array.find here.
Source: stackoverflow.com
Related Query
- How can you check if there is an existing value in the array and not add it another time if so?
- How can you check if there is the same item in an array and do something otherwise?
- How can i check if two state array shared the same value of not in React
- How can change the clone of an array and not change the original array in reactjs
- How to group arrays of objects by value and add the result to another array with same value at specific key
- How to consecutively add values from one array to another and store the value in a new array in javascript?
- How can I compare two arrays of objects and add new key to an objects in the second array
- How can I get all the object inside an object which is present inside an array and add the result into another array
- How can I check if the contents inside an iframe is fully loaded and the src url is not down(404/not available) using angular?
- How can we compare each element array and show the element based on the value
- React - How can i add new value to an array and display this array in alert window?
- How can I add new a new object with key and values pairs to the existing state in class based component?
- How can I add additional items to a store array and still be able to set the array to empty when resetting?
- setstate object:{array:[]} in reactjs how could i add the **key and value inside the array which is in the state object**?
- How do you check if value exists and then either add or update values in firebase with JavaScript?
- How i can limit the items in the FlatList and add load more?
- How can mock the value of a state and data in my react test
- How do i iterate over an array of object in react.js and add the values of prices in the object as shown below
- How can I not pass children as props. Instead, nest children between the opening and closing tags on React?
- How can I use Promise.all on an array of objects and then reassign them to the relevant key in a new object?
- How to add type FunctionComponent to React functional component using the "function" syntax and not "const"?
- Firestore - How can I add the Document ID and their data in my state?
- How to check the value of a nested React component in a unit test with Enzyme and Jest
- How to display and handle dynamic checkoxes that are dependent on Task array value in the backend (Mongodb) in react js?
- How can I check the return value of dispatch in redux hook
- React-Hook Form with useFieldArray: TextField value does not show up in the console. How can I fix it?
- How do I autofill the other autocomplete values based on the selected data and also add the data if it does not exist yet?
- How to construct an Array to first compare and then add the input
- In React.js, how can I loop through an array of jsx elements and add attributes to them
- How to check Api is triggered or not and how to abort the api if its triggered
More Query from same tag
- Material UI Tab pass props to component
- useFieldArray not reading data passed in to fields
- How to call a function every minute in a React component?
- Dynamically adding more `select` and it does not show the value anymore
- how to get array kets on selecting value from react search auto select
- Radio button with dynamic value from input as label
- React router how to click thru to detail components
- React admin access datagrid row value
- Reactjs handleChange for input field in a child component
- Mantaining component state when changing component placement
- NavItem return type in react, reactstrap
- React - how to copy an image to clipboard?
- Adding slimscroll to reactJS
- TypeError: Redux Action is not a function
- Get interface property compomponent props as types
- How to create nested stacknavigators in react native?
- React: clicking on an item in a list and print out its current state
- How to embed Landbot to Next.js application?
- Can a React component render another component stored in it's state?
- React/Webpack - Image not loading due to wrong path
- How to update a useState-hook with a condition in react?
- anyone have a good tutorial for react signature canvas
- How do I call a react router 4 redirect outside of the render function?
- Material-UI Nested Checkbox selection doesn't render change to parent in DOM
- How can i enable service worker in dev mode in create-react-app?
- Pass data from on component to another react
- How to set multiple object values when using Immutable JS map
- missing values from spread operator
- How to convert date into another format in JavaScript?
- react doing multiple api fetch