| 20 | } |
| 21 | |
| 22 | class ContextProviderComponent extends React.Component { |
| 23 | componentDidMount() { |
| 24 | if (typeof window !== 'undefined') { |
| 25 | const storageState = window.localStorage.getItem(STORAGE_KEY) |
| 26 | if (!storageState) { |
| 27 | window.localStorage.setItem(STORAGE_KEY, JSON.stringify(initialState)) |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | setItemQuantity = (item) => { |
| 33 | const storageState = JSON.parse(window.localStorage.getItem(STORAGE_KEY)) |
| 34 | const { cart } = storageState |
| 35 | const index = cart.findIndex(cartItem => cartItem.id === item.id) |
| 36 | cart[index].quantity = item.quantity |
| 37 | window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ |
| 38 | cart, numberOfItemsInCart: cart.length, total: calculateTotal(cart) |
| 39 | })) |
| 40 | this.forceUpdate() |
| 41 | } |
| 42 | |
| 43 | addToCart = item => { |
| 44 | const storageState = JSON.parse(window.localStorage.getItem(STORAGE_KEY)) |
| 45 | const { cart } = storageState |
| 46 | if (cart.length) { |
| 47 | const index = cart.findIndex(cartItem => cartItem.id === item.id) |
| 48 | if (index >= Number(0)) { |
| 49 | /* If this item is already in the cart, update the quantity */ |
| 50 | cart[index].quantity = cart[index].quantity + item.quantity |
| 51 | } else { |
| 52 | /* If this item is not yet in the cart, add it */ |
| 53 | cart.push(item) |
| 54 | } |
| 55 | } else { |
| 56 | /* If no items in the cart, add the first item. */ |
| 57 | cart.push(item) |
| 58 | } |
| 59 | |
| 60 | window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ |
| 61 | cart, numberOfItemsInCart: cart.length, total: calculateTotal(cart) |
| 62 | })) |
| 63 | toast("Successfully added item to cart!", { |
| 64 | position: toast.POSITION.TOP_LEFT |
| 65 | }) |
| 66 | this.forceUpdate() |
| 67 | } |
| 68 | |
| 69 | removeFromCart = (item) => { |
| 70 | const storageState = JSON.parse(window.localStorage.getItem(STORAGE_KEY)) |
| 71 | let { cart } = storageState |
| 72 | cart = cart.filter(c => c.id !== item.id) |
| 73 | |
| 74 | window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ |
| 75 | cart, numberOfItemsInCart: cart.length, total: calculateTotal(cart) |
| 76 | })) |
| 77 | this.forceUpdate() |
| 78 | } |
| 79 |
nothing calls this directly
no test coverage detected