I am trying to add the functionality of increasing items in my ecommerce project but when i increase value of one product it increases of all, how can I approach this differently so that it works the way I want it to.(check the stackblitz link for working example).
import React, { useState } from 'react';
const products = [
{ id: 1, clothe: 'pant' },
{ id: 2, clothe: 'shirt' },
{ id: 3, clothe: 'coat' },
];
const Cart = () => {
const [itemCount, setItemCount] = useState(0);
const increaseItem = () => {
setItemCount(itemCount 1);
};
const decreaseItem = () => {
setItemCount(itemCount - 1);
};
return (
<div>
{products.map((item) => (
<div>
<div> {item.clothe} </div>
<button onClick={() => increaseItem()}> </button>
<span>{itemCount}</span>
<button onClick={() => decreaseItem()}>-</button>
</div>
))}
</div>
);
};
export default Cart;
CodePudding user response:
Can you try this maintained separate state for each products.
import React, { useState } from 'react';
const Cart = () => {
const [products, setProducts] = useState([
{ id: 1, clothe: 'pant', count: 0 },
{ id: 2, clothe: 'shirt', count: 0 },
{ id: 3, clothe: 'coat', count: 0 },
]);
const [itemCount, setItemCount] = useState(0);
const increaseItem = (index, currentCount) => {
let uProducts = [...products];
uProducts[index].count = currentCount 1;
setProducts(uProducts);
};
const decreaseItem = (index, currentCount) => {
let uProducts = [...products];
uProducts[index].count = currentCount - 1;
setProducts(uProducts);
};
return (
<div>
{products.map((item, index) => (
<div>
<div> {item.clothe} </div>
<button onClick={(e) => increaseItem(index, item.count)}> </button>
<span>{item.count}</span>
<button onClick={(e) => decreaseItem(index, item.count)}>-</button>
</div>
))}
</div>
);
};
export default Cart;
CodePudding user response:
You must have separated count state of each product
.
import React, { useState } from 'react';
const products = [
{ id: 1, clothe: 'pant' },
{ id: 2, clothe: 'shirt' },
{ id: 3, clothe: 'coat' },
];
const Cart = () => {
const [itemCount, setItemCount] = useState(products.map((item, index) => 0));
const increaseItem = (index) => {
const _itemCount = [...itemCount];
_itemCount[index] ;
setItemCount(_itemCount);
};
const decreaseItem = (index) => {
const _itemCount = [...itemCount];
_itemCount[index]--;
setItemCount(_itemCount);
};
return (
<div>
{products.map((item, index) => (
<div>
<div> {item.clothe} </div>
<button onClick={() => increaseItem(index)}> </button>
<span>{itemCount[index]}</span>
<button onClick={() => decreaseItem(index)}>-</button>
</div>
))}
</div>
);
};
export default Cart;