type ProductState = {
entities: Product[]
loaded: boolean
loading: boolean
error: string | null
}
type ProductActions = {
add: (item: Product) => void
addMany: (items: Product[]) => void
update: (id: string, patch: Partial<Product>) => void
updateMany: (patches: (Pick<Product, 'id'> & Partial<Product>)[]) => void
delete: (id: string) => void
deleteMany: (ids: string[]) => void
find: (id: string) => Product | undefined
has: (id: string) => boolean
clear: () => void
replaceAll: (items: Product[]) => void
setLoading: (loading: boolean) => void
setError: (error: string | null) => void
}
export const useProductStore = create<ProductState & ProductActions>()((set, get) => ({
entities: [],
loaded: false,
loading: false,
error: null,
add: (item) =>
set((state) =>
state.entities.some((e) => e.id === item.id)
? { loaded: true, loading: false, error: `Item with id=${item.id} already exists.` }
: { entities: [...state.entities, item], loaded: true, loading: false, error: null }
),
addMany: (items) =>
set((state) => {
const seen = new Set(state.entities.map((e) => e.id))
const duplicates = new Set<string>()
for (const item of items) {
if (seen.has(item.id)) duplicates.add(item.id)
seen.add(item.id)
}
if (duplicates.size > 0) {
const ids = [...duplicates].join(', ')
return { loaded: true, loading: false, error: `Items with id=${ids} already exist.` }
}
return { entities: [...state.entities, ...items], loaded: true, loading: false, error: null }
}),
update: (id, patch) =>
set((state) => {
if (!state.entities.some((e) => e.id === id)) {
return { loading: false, error: `Item with id=${id} was not found.` }
}
if ('id' in patch && patch.id !== id && state.entities.some((e) => e.id === patch.id)) {
return {
loading: false,
error: `Cannot change id=${id} to ${patch.id}: an item with that id already exists.`,
}
}
return {
entities: state.entities.map((e) => (e.id === id ? { ...e, ...patch } : e)),
loading: false,
error: null,
}
}),
updateMany: (patches) =>
set((state) => ({
entities: state.entities.map((e) => {
const p = patches.find((x) => x.id === e.id)
return p ? { ...e, ...p } : e
}),
loading: false,
error: null,
})),
delete: (id) =>
set((state) =>
state.entities.some((e) => e.id === id)
? { entities: state.entities.filter((e) => e.id !== id), loading: false, error: null }
: { loading: false, error: `Item with id=${id} was not found.` }
),
deleteMany: (ids) =>
set((state) => ({
entities: state.entities.filter((e) => !ids.includes(e.id)),
loading: false,
error: null,
})),
find: (id) => get().entities.find((e) => e.id === id),
has: (id) => get().entities.some((e) => e.id === id),
clear: () => set({ entities: [], loaded: false, loading: false, error: null }),
replaceAll: (items) => set({ entities: items, loaded: true, loading: false, error: null }),
setLoading: (loading) => set({ loading }),
setError: (error) => set(error === null ? { error } : { error, loading: false }),
}))