improve: improved performance of menu list
This commit is contained in:
+36
-38
@@ -1,52 +1,50 @@
|
||||
// zustand/userStore.ts
|
||||
import { create } from 'zustand'
|
||||
import { createJSONStorage, persist } from 'zustand/middleware'
|
||||
// zustand/receiptStore.ts
|
||||
import { create } from 'zustand';
|
||||
import { createJSONStorage, persist } from 'zustand/middleware';
|
||||
|
||||
type ReceiptItem = {
|
||||
id: number
|
||||
quantity: number
|
||||
}
|
||||
type ReceiptItemMap = {
|
||||
[id: number]: {
|
||||
quantity: number;
|
||||
};
|
||||
};
|
||||
|
||||
type AuthStore = {
|
||||
items: Array<ReceiptItem>
|
||||
increment: (id: number) => void
|
||||
decrement: (id: number) => void
|
||||
clear: () => void
|
||||
}
|
||||
type ReceiptStore = {
|
||||
items: ReceiptItemMap;
|
||||
increment: (id: number) => void;
|
||||
decrement: (id: number) => void;
|
||||
clear: () => void;
|
||||
};
|
||||
|
||||
export const useReceiptStore = create<AuthStore>()(
|
||||
export const useReceiptStore = create<ReceiptStore>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
items: [],
|
||||
clear: () =>
|
||||
set(() => ({
|
||||
items: []
|
||||
})),
|
||||
items: {},
|
||||
clear: () => set({ items: {} }),
|
||||
increment: (id) =>
|
||||
set((state) => {
|
||||
if (state.items.find(x => x.id === id) === undefined) {
|
||||
return ({
|
||||
items: [...state.items, {id, quantity: 1}]
|
||||
})
|
||||
}
|
||||
return ({
|
||||
items: state.items.map((item) =>
|
||||
item.id === id ? { ...item, quantity: item.quantity + 1 } : item
|
||||
),
|
||||
})
|
||||
const current = state.items[id]?.quantity || 0;
|
||||
return {
|
||||
items: {
|
||||
...state.items,
|
||||
[id]: { quantity: current + 1 },
|
||||
},
|
||||
};
|
||||
}),
|
||||
decrement: (id) =>
|
||||
set((state) => ({
|
||||
items: state.items.map((item) =>
|
||||
item.id === id && item.quantity > 0
|
||||
? { ...item, quantity: item.quantity - 1 }
|
||||
: item
|
||||
),
|
||||
})),
|
||||
set((state) => {
|
||||
const current = state.items[id]?.quantity || 0;
|
||||
if (current <= 0) return {};
|
||||
return {
|
||||
items: {
|
||||
...state.items,
|
||||
[id]: { quantity: current - 1 },
|
||||
},
|
||||
};
|
||||
}),
|
||||
}),
|
||||
{
|
||||
name: 'receipt-storage', // Key in localStorage
|
||||
name: 'receipt-storage',
|
||||
storage: createJSONStorage(() => sessionStorage),
|
||||
}
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user