I am trying to add extra items to the Cart using useContext, but the code keeps crashing with the error of "TypeError: Cannot read property 'find' of undefined". I want to add the items in the Cart and I do not know if this code should work, perhaps i am doing something wrong.
This is the CartProvider code:
import { useState } from "react";
import CartContext from "./CartContext";
export const CartProvider = ({ children }) => {
const [list, setList] = useState();
const addCart = (varietals) => {
const isInCart = list.find((x) => x.id === varietals.id);
if (isInCart) {
setList(
list.map((x) =>
x.id === varietals.id ? { ...isInCart, qty: isInCart.qty + 1 } : x
)
);
}else{
setList([...list, { ...varietals, qty: 1 }]);
}
};
return(
<>
<CartContext.Provider value={{list, addCart}}>
{children}
</CartContext.Provider>
</>);
};
Varietals contains all the details of each item.