Skip to content
Zenty

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.

stores/products.ts
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)

zenty
// 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.

createEntitiesStore options
NameTypeDescription
idKeyK extends keyof TThe field that holds the unique ID. Required when it isn't called id.Default: 'id'
initialStateT[]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.
middlewareZentyMiddleware<EntitiesStoreState<T, K>>Zustand middleware such as persist or devtools. See the middleware guide.

State(link to this section)

createEntitiesStore state
NameTypeDescription
entitiesT[]The items, in insertion order.
loadedbooleanTrue once data has landed: a non-empty initialState, add, addMany or replaceAll. Only clear() sets it back to false.
loadingbooleanSet it with setLoading(true). Every write and setError('…') sets it back to false.
errorstring | nullThe last error message. A successful write clears it.

Actions(link to this section)

createEntitiesStore actions
NameTypeDescription
add(item: T) => voidAppends an item. Refuses an ID that already exists.
addMany(items: T[]) => voidAppends several items at once. If any ID exists or repeats in the batch, nothing is added.
update(id: T[K], patch: Partial<T>) => voidMerges 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>)[]) => voidApplies several patches; each one names its item by ID. IDs that don't exist are skipped without an error.
delete(id: T[K]) => voidRemoves one item. Sets error if the ID doesn't exist.
deleteMany(ids: T[K][]) => voidRemoves several items. IDs that don't exist are skipped without an error.
replaceAll(items: T[]) => voidReplaces the whole list, for example with a fresh API response.
clear() => voidEmpties the list and resets loaded, loading and error.
find(id: T[K]) => T | undefinedReturns the item with that ID.
has(id: T[K]) => booleanWhether an item with that ID exists.
setLoading(loading: boolean) => voidSets loading.
setError(error: string | null) => voidSets 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:

errors.ts
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 by createEntitiesStore.
  • 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.