1 | import { createContext, useReducer } from "react";
|
---|
2 |
|
---|
3 | export const Store = createContext();
|
---|
4 |
|
---|
5 | const initialState = {
|
---|
6 | userInfo: localStorage.getItem("userInfo")
|
---|
7 | ? JSON.parse(localStorage.getItem("userInfo"))
|
---|
8 | : null,
|
---|
9 | cart: {
|
---|
10 | shippingAddress: localStorage.getItem("shippingAddress")
|
---|
11 | ? JSON.parse(localStorage.getItem("shippingAddress"))
|
---|
12 | : {},
|
---|
13 | paymentMethod: localStorage.getItem("paymentMethod")
|
---|
14 | ? localStorage.getItem("paymentMethod")
|
---|
15 | : "",
|
---|
16 | cartItems: localStorage.getItem("cartItems")
|
---|
17 | ? JSON.parse(localStorage.getItem("cartItems"))
|
---|
18 | : [],
|
---|
19 | },
|
---|
20 | };
|
---|
21 |
|
---|
22 | function reducer(state, action) {
|
---|
23 | switch (action.type) {
|
---|
24 | case "CART_ADD_ITEM":
|
---|
25 | const newItem = action.payload;
|
---|
26 | const existItem = state.cart.cartItems.find(
|
---|
27 | (item) => item._id === newItem._id
|
---|
28 | );
|
---|
29 | const cartItems = existItem
|
---|
30 | ? state.cart.cartItems.map((item) =>
|
---|
31 | item._id === existItem._id ? newItem : item
|
---|
32 | )
|
---|
33 | : [...state.cart.cartItems, newItem];
|
---|
34 | localStorage.setItem("cartItems", JSON.stringify(cartItems));
|
---|
35 | return { ...state, cart: { ...state.cart, cartItems } };
|
---|
36 | case "CART_REMOVE_ITEM": {
|
---|
37 | const cartItems = state.cart.cartItems.filter(
|
---|
38 | (item) => item._id !== action.payload._id
|
---|
39 | );
|
---|
40 | localStorage.setItem("cartItems", JSON.stringify(cartItems));
|
---|
41 | return { ...state, cart: { ...state.cart, cartItems } };
|
---|
42 | }
|
---|
43 | case "CART_CLEAR":
|
---|
44 | return { ...state, cart: { ...state.cart, cartItems: [] } };
|
---|
45 | case "USER_SIGNIN":
|
---|
46 | return { ...state, userInfo: action.payload };
|
---|
47 | case "USER_SIGNOUT":
|
---|
48 | return {
|
---|
49 | ...state,
|
---|
50 | userInfo: null,
|
---|
51 | cart: { cartItems: [], shippingAddress: {}, paymentMethod: "" },
|
---|
52 | };
|
---|
53 | case "SAVE_SHIPPING_ADDRESS":
|
---|
54 | return {
|
---|
55 | ...state,
|
---|
56 | cart: { ...state.cart, shippingAddress: action.payload },
|
---|
57 | };
|
---|
58 | case "SAVE_PAYMENT_METHOD":
|
---|
59 | return {
|
---|
60 | ...state,
|
---|
61 | cart: { ...state.cart, paymentMethod: action.payload },
|
---|
62 | };
|
---|
63 | default:
|
---|
64 | return state;
|
---|
65 | }
|
---|
66 | }
|
---|
67 |
|
---|
68 | export function StoreProvider(props) {
|
---|
69 | const [state, dispatch] = useReducer(reducer, initialState);
|
---|
70 | const value = { state, dispatch };
|
---|
71 | return <Store.Provider value={value}>{props.children}</Store.Provider>;
|
---|
72 | }
|
---|