ecommerce_sanity_stripe
ecommerce_sanity_stripe copied to clipboard
product.name Resulting as "undefined" in the stateContext file
I was making this file, it worked fine but the toast said "(quantity) undefined added to cart" instead of the correct product name, So I tried copy pasting the stateContext.js file directly, same thing but in the video it worked just fine, how can I fix that?
export const StateContext = ({ children }) => {
const [showCart, setShowCart] = useState(false);
const [cartItems, setCartItems] = useState([]);
const [totalPrice, setTotalPrice] = useState(0);
const [totalQuantities, setTotalQuantities] = useState(0);
const [qty, setQty] = useState(1);
let foundProduct;
let index;
const onAdd = (product, quantity) => {
const checkProductInCart = cartItems.find((item) => item._id === product._id);
setTotalPrice((prevTotalPrice) => prevTotalPrice + product.price * quantity);
setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
if(checkProductInCart) {
const updatedCartItems = cartItems.map((cartProduct) => {
if(cartProduct._id === product._id) return {
...cartProduct,
quantity: cartProduct.quantity + quantity
}
})
setCartItems(updatedCartItems);
} else {
product.quantity = quantity;
setCartItems([...cartItems, { ...product }]);
}
toast.success(`${qty} ${product.name} added to the cart.`);
}
Did you pass the product and quantity from the 'Add to Cart' button properly? Like so:
<button type="button" className="add-to-cart" onClick={() => onAdd(product, qty)}>Add to Cart</button>