1

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
aDabOfRanch
  • 137
  • 9
  • the Item function component accepts item as its param, which I assume is passed in from an array of Items. on button click, it updates your cart array with the new item param – codemax Aug 20 '19 at 16:53
  • @codemax the "item" param in the Item functional component is coming from an array of products. This array is different than the cart array. – aDabOfRanch Aug 20 '19 at 16:56

0 Answers0