|
| 1 | +import {Commit, createLogger, createStore, Store} from "@visitsb/vuex"; |
| 2 | +import {Context, createContext, useContext, useEffect, useState} from "react"; |
| 3 | +import {CartItem, CartProduct, CartState, CheckoutStatus, Product, ProductsState, State} from "./../types"; |
| 4 | +import shop from '../api/shop' |
| 5 | + |
| 6 | +const debug = process.env.NODE_ENV !== 'production' |
| 7 | + |
| 8 | +export const store: Store<State> = createStore({ |
| 9 | + strict: debug, |
| 10 | + state: (): State => ({}), |
| 11 | + getters: {}, |
| 12 | + mutations: {}, |
| 13 | + actions: {}, |
| 14 | + modules: { |
| 15 | + products: { |
| 16 | + namespaced: true, |
| 17 | + state: (): ProductsState => ({ |
| 18 | + all: [] |
| 19 | + }), |
| 20 | + getters: {}, |
| 21 | + mutations: { |
| 22 | + setProducts(state: ProductsState, products: Product[]) { |
| 23 | + state.all = products |
| 24 | + }, |
| 25 | + decrementProductInventory(state: ProductsState, {id}: Product) { |
| 26 | + const product = state.all.find(product => product.id === id) |
| 27 | + product!.inventory-- |
| 28 | + } |
| 29 | + }, |
| 30 | + actions: { |
| 31 | + async getAllProducts({commit}: { commit: Commit }) { |
| 32 | + const products: Product[] = await shop.getProducts() |
| 33 | + commit('setProducts', products) |
| 34 | + } |
| 35 | + } |
| 36 | + }, |
| 37 | + cart: { |
| 38 | + namespaced: true, |
| 39 | + state: (): CartState => ({ |
| 40 | + items: [], |
| 41 | + checkoutStatus: CheckoutStatus.EMPTY |
| 42 | + }), |
| 43 | + getters: { |
| 44 | + cartProducts: (state: CartState, getters: any, rootState: State): CartProduct[] => { |
| 45 | + return state.items.map(({id, quantity}): CartProduct => { |
| 46 | + const product: Product = rootState.products.all.find((product: Product) => (product.id === id)) |
| 47 | + return <CartProduct>{ |
| 48 | + id: product.id, |
| 49 | + title: product.title, |
| 50 | + price: product.price, |
| 51 | + quantity |
| 52 | + } |
| 53 | + }) |
| 54 | + }, |
| 55 | + cartTotalItems: (state: CartState, getters: any): number => { |
| 56 | + return getters.cartProducts.reduce((total: number, product: CartProduct) => { |
| 57 | + return total + product.quantity |
| 58 | + }, 0) |
| 59 | + }, |
| 60 | + cartTotalPrice: (state: CartState, getters: any): number => { |
| 61 | + return getters.cartProducts.reduce((total: number, product: CartProduct) => { |
| 62 | + return total + product.price * product.quantity |
| 63 | + }, 0) |
| 64 | + } |
| 65 | + }, |
| 66 | + mutations: { |
| 67 | + pushProductToCart(state: CartState, {id}: Partial<Product> & { id: number }) { |
| 68 | + state.items.push({id, quantity: 1}) |
| 69 | + }, |
| 70 | + |
| 71 | + incrementItemQuantity(state: CartState, {id}: Partial<Product> & { id: number }) { |
| 72 | + const cartItem: CartItem = state.items.find(item => item.id === id)! |
| 73 | + cartItem.quantity++ |
| 74 | + }, |
| 75 | + |
| 76 | + setCartItems(state: CartState, {items}: { items: CartItem[] }): void { |
| 77 | + state.items = items |
| 78 | + }, |
| 79 | + |
| 80 | + setCheckoutStatus(state: CartState, status: CheckoutStatus = CheckoutStatus.EMPTY): void { |
| 81 | + state.checkoutStatus = status |
| 82 | + } |
| 83 | + }, |
| 84 | + actions: { |
| 85 | + async checkout({ |
| 86 | + commit, |
| 87 | + state |
| 88 | + }: { commit: Commit, state: CartState }, products: Product[]): Promise<void> { |
| 89 | + commit('setCheckoutStatus') |
| 90 | + try { |
| 91 | + await shop.buyProducts(products) |
| 92 | + // empty cart |
| 93 | + commit('setCartItems', {items: []}) |
| 94 | + commit('setCheckoutStatus', CheckoutStatus.SUCCESSFUL) |
| 95 | + } catch (e) { |
| 96 | + // Log error somewhere |
| 97 | + commit('setCheckoutStatus', CheckoutStatus.FAILED) |
| 98 | + } |
| 99 | + }, |
| 100 | + |
| 101 | + async addProductToCart({ |
| 102 | + state, |
| 103 | + commit |
| 104 | + }: { state: CartState, commit: Commit }, product: Product): Promise<void> { |
| 105 | + commit('setCheckoutStatus') |
| 106 | + |
| 107 | + if (product.inventory > 0) { |
| 108 | + const cartItem: CartItem = state.items.find(item => item.id === product.id)! |
| 109 | + |
| 110 | + if (!cartItem) { |
| 111 | + commit('pushProductToCart', {id: product.id}) |
| 112 | + } else { |
| 113 | + commit('incrementItemQuantity', cartItem) |
| 114 | + } |
| 115 | + |
| 116 | + // remove 1 item from stock |
| 117 | + commit('products/decrementProductInventory', {id: product.id}, {root: true}) |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + }, |
| 123 | + plugins: debug ? [ |
| 124 | + createLogger<State>({ |
| 125 | + collapsed: true, |
| 126 | + transformer: () => '...', // Skip log for state |
| 127 | + actionTransformer: JSON.stringify, |
| 128 | + mutationTransformer: JSON.stringify |
| 129 | + }) |
| 130 | + ] : [/*no plugins*/] |
| 131 | +}) |
| 132 | + |
| 133 | +export const StoreContext: Context<Store<State>> = createContext(store); |
| 134 | +export const StateContext: Context<State> = createContext(store.state); |
| 135 | + |
| 136 | +export default function useStore() { |
| 137 | + const store = useContext<Store<State>>(StoreContext); |
| 138 | + const state = useContext<State>(StateContext); |
| 139 | + |
| 140 | + // Provider can expose a global variable |
| 141 | + // but it needs to be reactive in order to cause a re-render |
| 142 | + // which is different to Vuex - hence subscribe to state changes |
| 143 | + // and refresh a `react`-ive state which Provider understands |
| 144 | + let [watchedState, setWatchedState] = useState(state); |
| 145 | + |
| 146 | + useEffect((/*didUpdate*/) => { |
| 147 | + const unsubscribe = store.subscribe((mutation, newState) => setWatchedState((prevState: State) => ({...prevState, ...newState}))); |
| 148 | + |
| 149 | + return (/*cleanup*/) => unsubscribe() |
| 150 | + }, []); |
| 151 | + |
| 152 | + const _globalThis = (globalThis || self || window || global || {}); |
| 153 | + if (typeof _globalThis.$store === 'undefined') { |
| 154 | + _globalThis.$store = store; |
| 155 | + } |
| 156 | + |
| 157 | + return {store, state: watchedState}; |
| 158 | +} |
0 commit comments