add reducer in cart context

main
oscar 2023-03-18 21:49:26 +13:00
parent d7ef59f2a6
commit aa91bcea73
1 changed files with 30 additions and 4 deletions

View File

@ -1,12 +1,38 @@
import { useReducer } from "react";
import CartContext from "./cart-context";
const CartProvider = (props) => {
const addItemToCartHandler = (item) => {};
const removeItemFromCartHandler = (id) => {};
const cartContext = {
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 [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: cartState.items,
totalAmount: cartState.totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};