105 lines
2.2 KiB
TypeScript
105 lines
2.2 KiB
TypeScript
import toast from 'react-hot-toast'
|
|
import {create} from 'zustand'
|
|
import {persist} from 'zustand/middleware'
|
|
|
|
export interface CartItem {
|
|
id: number
|
|
quantity: number
|
|
title: string
|
|
price: string | any
|
|
image?: string | null
|
|
imageWidth?: number | null
|
|
imageHeight?: number | null
|
|
}
|
|
|
|
interface CartState {
|
|
cartItems: CartItem[]
|
|
addItemToCart: (item: CartItem) => void
|
|
increaseQuantity: (productId: number) => void
|
|
decreaseQuantity: (productId: number) => void
|
|
removeItemFromCart: (productId: number) => void
|
|
clearCart: () => void
|
|
}
|
|
|
|
const useCartStore = create(
|
|
persist<CartState>(
|
|
(set, get) => ({
|
|
cartItems: [],
|
|
|
|
addItemToCart: item => {
|
|
const itemExists = get().cartItems.find(
|
|
cartItem => cartItem.id === item.id
|
|
)
|
|
|
|
if (itemExists) {
|
|
if (typeof itemExists.quantity === 'number') {
|
|
itemExists.quantity++
|
|
}
|
|
|
|
set({cartItems: [...get().cartItems]})
|
|
} else {
|
|
set({cartItems: [...get().cartItems, {...item, quantity: 1}]})
|
|
}
|
|
},
|
|
|
|
increaseQuantity: productId => {
|
|
const itemExists = get().cartItems.find(
|
|
cartItem => cartItem.id === productId
|
|
)
|
|
|
|
if (itemExists) {
|
|
if (typeof itemExists.quantity === 'number') {
|
|
itemExists.quantity++
|
|
}
|
|
|
|
set({cartItems: [...get().cartItems]})
|
|
}
|
|
},
|
|
|
|
decreaseQuantity: productId => {
|
|
const itemExists = get().cartItems.find(
|
|
cartItem => cartItem.id === productId
|
|
)
|
|
|
|
if (itemExists) {
|
|
if (typeof itemExists.quantity === 'number') {
|
|
if (itemExists.quantity === 1) {
|
|
const updatedCartItems = get().cartItems.filter(
|
|
item => item.id !== productId
|
|
)
|
|
set({cartItems: updatedCartItems})
|
|
} else {
|
|
itemExists.quantity--
|
|
set({cartItems: [...get().cartItems]})
|
|
}
|
|
}
|
|
}
|
|
},
|
|
|
|
removeItemFromCart: productId => {
|
|
const itemExists = get().cartItems.find(
|
|
cartItem => cartItem.id === productId
|
|
)
|
|
|
|
if (itemExists) {
|
|
if (typeof itemExists.quantity === 'number') {
|
|
const updatedCartItems = get().cartItems.filter(
|
|
item => item.id !== productId
|
|
)
|
|
set({cartItems: updatedCartItems})
|
|
}
|
|
}
|
|
},
|
|
|
|
clearCart: () => {
|
|
set({cartItems: []})
|
|
}
|
|
}),
|
|
{
|
|
name: 'cart-items'
|
|
}
|
|
)
|
|
)
|
|
|
|
export default useCartStore
|