1 | import { createContext, useReducer } from "react";
|
---|
2 |
|
---|
3 | export const Store = createContext();
|
---|
4 |
|
---|
5 | const initialState = {
|
---|
6 | cart: {
|
---|
7 | cartItems: localStorage.getItem("cartItems")
|
---|
8 | ? JSON.parse(localStorage.getItem("cartItems"))
|
---|
9 | : [],
|
---|
10 | },
|
---|
11 | };
|
---|
12 |
|
---|
13 | function reducer(state, action) {
|
---|
14 | switch (action.type) {
|
---|
15 | case "CART_ADD_ITEM":
|
---|
16 | const newItem = action.payload;
|
---|
17 | const existItem = state.cart.cartItems.find(
|
---|
18 | (item) => item._id === newItem._id
|
---|
19 | );
|
---|
20 | const cartItems = existItem
|
---|
21 | ? state.cart.cartItems.map((item) =>
|
---|
22 | item._id === existItem._id ? newItem : item
|
---|
23 | )
|
---|
24 | : [...state.cart.cartItems, newItem];
|
---|
25 | localStorage.setItem("cartItems", JSON.stringify(cartItems));
|
---|
26 | return { ...state, cart: { ...state.cart, cartItems } };
|
---|
27 | case "CART_REMOVE_ITEM": {
|
---|
28 | const cartItems = state.cart.cartItems.filter(
|
---|
29 | (item) => item._id !== action.payload._id
|
---|
30 | );
|
---|
31 | localStorage.setItem("cartItems", JSON.stringify(cartItems));
|
---|
32 | return { ...state, cart: { ...state.cart, cartItems } };
|
---|
33 | }
|
---|
34 | default:
|
---|
35 | return state;
|
---|
36 | }
|
---|
37 | }
|
---|
38 |
|
---|
39 | export function StoreProvider(props) {
|
---|
40 | const [state, dispatch] = useReducer(reducer, initialState);
|
---|
41 | const value = { state, dispatch };
|
---|
42 | return <Store.Provider value={value}>{props.children}</Store.Provider>;
|
---|
43 | }
|
---|