-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.tsx
82 lines (69 loc) · 1.9 KB
/
context.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { ICartItem } from './models/cart'
import { createContext, useContext, useEffect, useState } from 'react'
import { products } from './data'
import { useLocalStorage } from 'usehooks-ts'
interface IProps {
children: React.ReactNode
}
const CartContext = createContext<any>(null)
export const CartProvider: React.FC<IProps> = ({ children }) => {
const [cart, setCart] = useLocalStorage<ICartItem[] | null>('cart', null)
const clearCart = () => {
setCart([])
}
const updateCart = (id: number, isDecrease?: boolean) => {
const isExist = cart?.find((item: ICartItem) => item.id === id)
if (!isExist) {
return false
}
if (isExist.quantity === 1 && isDecrease) {
return cart?.filter(obj => {
return obj.id !== id
})
}
return cart?.map(obj => {
if (obj.id === id) {
return {
...obj,
quantity: isDecrease ? isExist.quantity - 1 : isExist.quantity + 1,
}
}
return obj
})
}
const decrease = (id: number) => {
const newCart = updateCart(id, true)
if (newCart) {
setCart(newCart)
}
}
const increase = (id: number) => {
const newCart = updateCart(id)
if (newCart) {
setCart(newCart)
} else {
const product = { quantity: 1, id: id }
setCart(prev => (prev ? [...prev, product] : [product]))
}
}
const removeAllItems = (id: number) => {
const newCartItems = cart?.filter((item) => item.id !== id);
setCart(newCartItems);
}
useEffect(() => {
cart?.forEach(item => {
const { id, quantity } = item
if (quantity > 3 || quantity < 0 || id > products.length || id <= 0) {
setCart([])
}
})
}, [cart])
return (
<CartContext.Provider value={{ cart, increase, decrease, clearCart, removeAllItems }}>
{children}
</CartContext.Provider>
)
}
export function useCart() {
return useContext(CartContext)
}