add reducer in cart context
This commit is contained in:
parent
d7ef59f2a6
commit
aa91bcea73
@ -1,12 +1,38 @@
|
|||||||
|
import { useReducer } from "react";
|
||||||
import CartContext from "./cart-context";
|
import CartContext from "./cart-context";
|
||||||
|
|
||||||
const CartProvider = (props) => {
|
const defaultCartState = {
|
||||||
const addItemToCartHandler = (item) => {};
|
|
||||||
const removeItemFromCartHandler = (id) => {};
|
|
||||||
|
|
||||||
const cartContext = {
|
|
||||||
items: [],
|
items: [],
|
||||||
totalAmount: 0,
|
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,
|
addItem: addItemToCartHandler,
|
||||||
removeItem: removeItemFromCartHandler,
|
removeItem: removeItemFromCartHandler,
|
||||||
};
|
};
|
||||||
|
Loading…
Reference in New Issue
Block a user