I'm building an app that mimics an e-commerce site, and I don't know how I can add items to my cart.
I created a Context Provider. It contains an object which contains a array to hold all potential items in the cart. (I know I can just use an array in place of a list, but I plan to add other fields to this object).
import React, { createContext, useState } from 'react';
export const CartContext = createContext();
export const CartContextProvider = (props) => {
const [cart, setCart] = useState({items: []});
return(
<CartContext.Provider value={[cart, setCart]}>
{props.children}
</CartContext.Provider>
);
}
Next, I have an Item component.
const Item = ( {item} ) => {
const [cart, setCart] = useContext(CartContext);
const handleClick = e => {
setCart(prevCartItems => ({...prevCartItems, items: items.push(item)}));
}
console.log(cart.items);
return(
<div className="item">
<div className="product">
<h2>{item.name} : ${item.price}</h2>
<p>Category: {item.category}</p>
</div>
<button onClick={handleClick} className="add-to-cart">Add to Cart</button>
</div>
);
}
My confusion particularly lies in the handleClick
function in the Item
component where I'm updating the state of the cart. How do I add my item to the array? I'm making use of the spread
operator to copy the previous state, but how do I add my "new" item to the list?