From aa91bcea735e1ebcc7bf8a8c919954ef5081fb71 Mon Sep 17 00:00:00 2001 From: oscar Date: Sat, 18 Mar 2023 21:49:26 +1300 Subject: [PATCH] add reducer in cart context --- src/store/CartProvider.js | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/store/CartProvider.js b/src/store/CartProvider.js index 09af01b..ac960e1 100644 --- a/src/store/CartProvider.js +++ b/src/store/CartProvider.js @@ -1,12 +1,38 @@ +import { useReducer } from "react"; import CartContext from "./cart-context"; +const defaultCartState = { + items: [], + totalAmount: 0, +}; + +const cartReducer = (state, action) => { + if (action.type === "ADD_ITEM") { + const updatedItems = state.items.concat(action.item); + const updatedTotalAmount = + state.totalAmount + action.item.price * action.item.amount; + return { items: updatedItems, totalAmount: updatedTotalAmount }; + } else if (action.type === "REMOVE_ITEM") { + } + return defaultCartState; +}; + const CartProvider = (props) => { - const addItemToCartHandler = (item) => {}; - const removeItemFromCartHandler = (id) => {}; + const [cartState, dispatchCartAction] = useReducer( + cartReducer, + defaultCartState + ); + + const addItemToCartHandler = (item) => { + dispatchCartAction({ type: "ADD_ITEM", item: item }); + }; + const removeItemFromCartHandler = (id) => { + dispatchCartAction({ type: "REMOVE_ITEM", id: id }); + }; const cartContext = { - items: [], - totalAmount: 0, + items: cartState.items, + totalAmount: cartState.totalAmount, addItem: addItemToCartHandler, removeItem: removeItemFromCartHandler, };