Skip to content
Zenty

Zustand middleware

Use persist, devtools or your own Zustand middleware with Zenty stores, fully typed, and keep loaded in sync when persisting.

Applies to zenty v1.1.0

The middleware option(link to this section)

Both createEntitiesStore and createEntityStore take a middleware function. It receives the store initializer and returns the wrapped one, the same shape Zustand middleware already has. Compose several by nesting them:

stores/products.ts
import { devtools, persist } from 'zustand/middleware'
import { createEntitiesStore } from 'zenty'

type Product = { id: string; name: string; price?: number }

export const useProducts = createEntitiesStore<Product>({
  middleware: (config) => devtools(persist(config, { name: 'products' }), { name: 'products' }),
})

persist and partialize(link to this section)

The middleware is typed against the store's real state, so options like partialize get autocompletion and type errors without casts.

stores/products.ts
import { persist } from 'zustand/middleware'
import { createEntitiesStore } from 'zenty'

type Product = { id: string; name: string; price?: number }

export const useProducts = createEntitiesStore<Product>({
  middleware: (config) =>
    persist(config, {
      name: 'products',
      // state is fully typed. Keep loaded next to the data.
      partialize: (state) => ({ entities: state.entities, loaded: state.loaded }),
    }),
})

Reusable, typed middleware(link to this section)

To define a middleware once and share it, type it with ZentyMiddleware and the state type of the store it wraps: EntitiesStoreState<T, K> for lists, EntityStoreState<T, D> for single objects.

stores/users.ts
import { persist } from 'zustand/middleware'
import { createEntitiesStore } from 'zenty'
import type { EntitiesStoreState, ZentyMiddleware } from 'zenty'

interface User { userId: string; name: string; email: string }

const persistUsers: ZentyMiddleware<EntitiesStoreState<User, 'userId'>> = (config) =>
  persist(config, { name: 'users' })

export const useUsers = createEntitiesStore<User, 'userId'>({
  idKey: 'userId',
  middleware: persistUsers,
})

Found a mistake? Open an issue.