add reducer in cart context

This commit is contained in:
oscar 2023-03-18 21:49:26 +13:00
parent d7ef59f2a6
commit aa91bcea73

View File

@ -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,
};