UNPKG

cart

Version:

Headless cart management library

106 lines 2.93 kB
import AsyncStorage from "@react-native-async-storage/async-storage"; import { useEffect, useState } from "react"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; const isBrowser = typeof window.document !== "undefined"; const storageType = isBrowser ? localStorage : AsyncStorage; const setCartStoreName = (name) => { useCart.persist.setOptions({ name }); }; const withSSR = (store, callback) => { const result = store(callback); const [data, setData] = useState(); useEffect(() => { setData(result); }, [result]); return data; }; const setCartStoreType = (storage = localStorage) => { useCart.persist.setOptions({ storage: createJSONStorage(() => storage) }); }; const useCart = create()( persist( (set) => ({ addToCart: (item) => { set((state) => { const cartItems = state.cartItems ?? []; const itemInCart = cartItems.find( (i) => i.productId === item.productId ); if (itemInCart) { return { cartItems: cartItems.map((i) => { if (i.productId === item.productId) { return { ...i, quantity: i.quantity + 1 }; } return i; }) }; } else { return { cartItems: [...cartItems, { ...item, quantity: 1 }] }; } }); }, cartItems: [], clearCart: () => { set({ cartItems: [] }); }, closeCart: () => { set({ isCartOpen: false }); }, decreaseItem: (productId, quantity) => { set((state) => { if (quantity === void 0) { return { cartItems: state.cartItems?.filter( (item) => item.productId !== productId ) }; } const updatedCartItems = state.cartItems?.map((item) => { if (item.productId === productId) { const newQuantity = item.quantity - quantity; if (newQuantity <= 0) { return null; } return { ...item, quantity: newQuantity }; } return item; }).filter(Boolean); return { cartItems: updatedCartItems }; }); }, isCartOpen: false, openCart: () => { set({ isCartOpen: true }); }, removeFromCart: (productId) => { set((state) => ({ cartItems: state.cartItems?.filter( (item) => item.productId !== productId ) })); }, toggleCart: () => { set((state) => ({ isCartOpen: !state.isCartOpen })); } }), { name: "cart", storage: createJSONStorage(() => storageType) } ) ); export { setCartStoreName, setCartStoreType, useCart, withSSR }; //# sourceMappingURL=cart.js.map