I want to delete items from shopping cart with context API. I want to delete items one by one. For example there are five count from a product, I want to say if there's more than one product minus one by one, else (there is only one) delete whole product
Items data come from JSON file
First I used this code
import { createContext, useState } from "react";
const CartContext = createContext();
export function CartProvider({ children }) {
const [items , setItems] = useState([]);
const AddToCart = (photo,price,title,des,id,count)=>{
const product = items.find(item=> item.id === id);
if (product) {
product.count =1 ;
const products = items.find(item=> item.id !== id);
items.count =1;
return[...products, product]
}
setItems((prevState) => [...prevState, {photo,price,title,des,id,count}]);
}
const DeleteItemCart = (id) => {
const product = items.find(item=> item.id === id);
if(product.count>1){
product.count -=1;
}
else{
const deleted = items.filter((product) => parseInt(product.id) !== parseInt(id));
setItems(deleted);}
};
return <CartContext.Provider value={{items,AddToCart,DeleteItemCart}}>
{children}
</CartContext.Provider>;
}
export default CartContext;
In console.log everything is right and number of items reduced one by one. But it did not work in page and items number was fixed.
I supposed it's better to put count in a state so I write this code
const product = items.find(item=> item.id === id);
const[counter, setCounter] = useState(product.count)
const DeleteItemCart = (id) => {
if(counter>1){
const prev =product.count
setCounter(prev => prev-1)
console.log(counter)
}
else{
const deleted = items.filter((product) => product.id !== id);
setItems(deleted);}
};
but still have error
CodePudding user response:
try to convert your data into integer for your ID.
eg:- Try this method
const DeleteItemCart = (id) => {
const newTemp = [...items];
const product = newTemp.find(item=> parseInt(item.id) === parseInt(id));
if(product.count>1){
product.count -=1;
setItems(newTemp);// you missed this after reducing to 1
}
else{
const deleted = items.filter((product) => parseInt(product.id) !== parseInt(id));
setItems(deleted);}
};
CodePudding user response:
Share where the "items" array comes from (the Context Wrapper?).
Also, you can't use setters in component's code directly, it should be executed in "useEffect".
Is DeleteItemCart supposed to be a JSX component or it's a function? If it's a function, the first letter should be lowercase.
I will edit my answer when I get more details from you!
See my comment below...