source: frontend/src/Store.js@ b612ab1

Last change on this file since b612ab1 was b612ab1, checked in by Nace Gjorgjievski <nace.gorgievski123@…>, 23 months ago

Basic functions added

  • Property mode set to 100644
File size: 1.3 KB
Line 
1import { createContext, useReducer } from "react";
2
3export const Store = createContext();
4
5const initialState = {
6 cart: {
7 cartItems: localStorage.getItem("cartItems")
8 ? JSON.parse(localStorage.getItem("cartItems"))
9 : [],
10 },
11};
12
13function 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
39export 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}
Note: See TracBrowser for help on using the repository browser.