cart mechanism complete
This commit is contained in:
96
store/cart-store.ts
Normal file
96
store/cart-store.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
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
|
||||
}
|
||||
|
||||
interface CartState {
|
||||
cartItems: CartItem[]
|
||||
addItemToCart: (item: CartItem) => void
|
||||
increaseQuantity: (productId: number) => void
|
||||
decreaseQuantity: (productId: number) => void
|
||||
removeItemFromCart: (productId: number) => 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})
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
{
|
||||
name: 'cart-items'
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
export default useCartStore
|
||||
Reference in New Issue
Block a user