Custom IDs and your own actions
Use an ID field that isn't called id with idKey, and replace individual actions such as add or delete with your own logic.
Applies to zenty v1.1.0
An ID field that isn't id(link to this section)
APIs often call the key userId, sku or slug. Pass it as idKey and the second type parameter. Every action that takes an ID is then typed against that field, and duplicate checks use it.
import { createEntitiesStore } from 'zenty'
interface User {
userId: string
name: string
email: string
}
const useUsers = createEntitiesStore<User, 'userId'>({
idKey: 'userId',
initialState: [{ userId: '1', name: 'John', email: 'john@example.com' }],
})
useUsers.getState().update('1', { name: 'John Doe' }) // the ID is typed as User['userId']The field must hold a string or a number. Error messages name it, for example “Item with userId=1 already exists.”
Replace an action(link to this section)
add, addMany, update, updateMany, delete and deleteMany can each be replaced. Your function gets the action's arguments plus the current state, and returns the new list. Zenty stores it, marks the store as loaded where that applies, and ends loading.
import { createEntitiesStore } from 'zenty'
type Product = {
id: string
name: string
price?: number
createdAt?: Date
deleted?: boolean
}
const useProducts = createEntitiesStore<Product>({
// your own validation and defaults
add: (item, state) => {
if (state.entities.some((p) => p.name === item.name)) {
throw new Error('Product name must be unique')
}
return [...state.entities, { ...item, createdAt: new Date() }]
},
// soft delete instead of removing the item
delete: (id, state) => state.entities.map((p) => (p.id === id ? { ...p, deleted: true } : p)),
})Override only what you need(link to this section)
You don't have to replace everything. Pass one function and keep the defaults for the rest:
import { createEntitiesStore } from 'zenty'
type Product = { id: string; name: string; price?: number }
// keep the list sorted by name; every other action stays the default
export const useSorted = createEntitiesStore<Product>({
add: (item, state) => [...state.entities, item].sort((a, b) => a.name.localeCompare(b.name)),
})Found a mistake? Open an issue.