createEntitiesStore
API reference for createEntitiesStore: signatures, options, state, every action and the built-in rules for duplicate and missing IDs.
Applies to zenty v1.1.0
createEntitiesStore creates a Zustand store for a list of items that each have a unique ID. It returns the hook you'd get from Zustand's create(), with the state and actions below already in place.
import { createEntitiesStore } from 'zenty'
type Product = { id: string; name: string; price?: number }
export const useProducts = createEntitiesStore<Product>({
initialState: [{ id: 'p1', name: 'Desk lamp', price: 39 }],
})
const { add, update, find } = useProducts.getState()
add({ id: 'p2', name: 'Monitor arm', price: 89 })
update('p1', { price: 35 })
find('p1') // { id: 'p1', name: 'Desk lamp', price: 35 }Signature(link to this section)
// T has an 'id' field: idKey is optional
function createEntitiesStore<T extends { id: string | number }>(
options?: Omit<EntitiesStoreOptions<T, 'id'>, 'idKey'> & { idKey?: 'id' }
): EntitiesStore<T, 'id'>
// any other ID field: idKey is required
function createEntitiesStore<T extends Record<K, string | number>, K extends keyof T>(
options: EntitiesStoreOptions<T, K>
): EntitiesStore<T, K>
// EntitiesStore<T, K> = UseBoundStore<StoreApi<EntitiesState<T> & EntitiesActions<T, K>>>Options(link to this section)
All options are optional when your type has an id field.
| Name | Type | Description |
|---|---|---|
idKey | K extends keyof T | The field that holds the unique ID. Required when it isn't called id.Default: 'id' |
initialState | T[] | Items the store starts with. A non-empty list starts with loaded: true.Default: [] |
add, addMany, update, updateMany, delete, deleteMany | (…args, state) => T[] | Your own version of an action. It gets the action's arguments plus the current state and returns the new list. Errors you throw end up in error. See replacing an action. |
middleware | ZentyMiddleware<EntitiesStoreState<T, K>> | Zustand middleware such as persist or devtools. See the middleware guide. |
State(link to this section)
| Name | Type | Description |
|---|---|---|
entities | T[] | The items, in insertion order. |
loaded | boolean | True once data has landed: a non-empty initialState, add, addMany or replaceAll. Only clear() sets it back to false. |
loading | boolean | Set it with setLoading(true). Every write and setError('…') sets it back to false. |
error | string | null | The last error message. A successful write clears it. |
Actions(link to this section)
| Name | Type | Description |
|---|---|---|
add | (item: T) => void | Appends an item. Refuses an ID that already exists. |
addMany | (items: T[]) => void | Appends several items at once. If any ID exists or repeats in the batch, nothing is added. |
update | (id: T[K], patch: Partial<T>) => void | Merges the patch into one item (shallow). Sets error if the ID doesn't exist. Can change the ID, unless the new one is taken. |
updateMany | (patches: (Pick<T, K> & Partial<T>)[]) => void | Applies several patches; each one names its item by ID. IDs that don't exist are skipped without an error. |
delete | (id: T[K]) => void | Removes one item. Sets error if the ID doesn't exist. |
deleteMany | (ids: T[K][]) => void | Removes several items. IDs that don't exist are skipped without an error. |
replaceAll | (items: T[]) => void | Replaces the whole list, for example with a fresh API response. |
clear | () => void | Empties the list and resets loaded, loading and error. |
find | (id: T[K]) => T | undefined | Returns the item with that ID. |
has | (id: T[K]) => boolean | Whether an item with that ID exists. |
setLoading | (loading: boolean) => void | Sets loading. |
setError | (error: string | null) => void | Sets error. A message also ends loading; null keeps loading as it is. |
Built-in rules(link to this section)
Zenty keeps the list consistent instead of failing silently. When a write can't be applied, it sets error and leaves the list unchanged:
const { add, addMany, update } = useProducts.getState()
const error = () => useProducts.getState().error // read fresh state
add({ id: 'p1', name: 'Lamp' })
add({ id: 'p1', name: 'Lamp' })
error() // "Item with id=p1 already exists."
addMany([{ id: 'p2', name: 'Desk' }, { id: 'p1', name: 'Dup' }])
error() // "Items with id=p1 already exist." (p2 is not added either)
update('missing', { name: 'Nope' })
error() // "Item with id=missing was not found."
add({ id: 'p2', name: 'Desk' }) // succeeds and clears the error
update('p1', { id: 'p2' })
error() // "Cannot change id=p1 to p2: an item with that id already exists."Exported types(link to this section)
Useful when you pass stores or state around:
EntitiesStore<T, K>: the hook type returned bycreateEntitiesStore.EntitiesStoreState<T, K>: state and actions together, as middleware sees them.EntitiesState<T>,EntitiesActions<T, K>,EntitiesStoreOptions<T, K>.
Found a mistake? Open an issue.