I am currently working on implementing shopping cart functionality in Next.js using Zustand. However, I encounter an issue when attempting to count the total number of items in the cart upon adding an item or when the increase/decrease buttons are clicked. The code snippet I'm using is const state = set.getState();
, but it results in the following error:
Property 'getState' does not exist on type '(partial: CartState | Partial | ((state: CartState) => CartState | Partial), replace?: boolean | undefined) => void'.
Could you please provide guidance on how to resolve this error and correctly retrieve the total number of items in the shopping cart using Zustand in Next.js?
Here is the full code:
// cart.ts
import create from 'zustand';
interface CartState {
items: { id: number; name: string; price: number; quantity: number }[];
addToCart: (item: { id: number; name: string; price: number }) => void;
removeFromCart: (itemId: number) => void;
increaseQuantity: (itemId: number) => void;
decreaseQuantity: (itemId: number) => void;
getTotalItems: () => number;
}
export const useCart = create<CartState>((set) => ({
items: [],
addToCart: (item) =>
set((state) => ({ items: [...state.items, { ...item, quantity: 1 }] })),
removeFromCart: (itemId) =>
set((state) => ({ items: state.items.filter((item) => item.id !== itemId) })),
increaseQuantity: (itemId) =>
set((state) => ({
items: state.items.map((item) =>
item.id === itemId ? { ...item, quantity: item.quantity + 1 } : item
),
})),
decreaseQuantity: (itemId) =>
set((state) => ({
items: state.items.map((item) =>
item.id === itemId ? { ...item, quantity: Math.max(1, item.quantity - 1) } : item
),
})),
getTotalItems: () => {
const state = set.getState();
return state.items.reduce((acc: any, item: { quantity: any; }) => acc + item.quantity, 0);
},
}));
according to the document you should use getState()
this way:
// Getting non-reactive fresh state
const paw = useDogStore.getState().paw
I recommend receiving get
and using it retrieve data
export const useCart = create<CartState>((set, get) => ({
.
.
.
getTotalItems: () => {
const state = get().items;
return state.items.reduce((acc: any, item: { quantity: any; }) => acc + item.quantity, 0);
},