Repository navigation
How to creating autogenerated selectors using the slice pattern method? #3141
Unanswered
gil-obradors
asked this question in
Q&A
Replies: 1 comment
|
Yes. Combine the slices into one store first, then apply Using the import { create, type StateCreator } from 'zustand';
import { createSelectors } from './create-selectors';
type BearSlice = { bears: number; addBear: () => void };
type FishSlice = { fishes: number; addFish: () => void };
type State = BearSlice & FishSlice;
const createBearSlice: StateCreator<State, [], [], BearSlice> = (set) => ({
bears: 0,
addBear: () => set((s) => ({ bears: s.bears + 1 })),
});
const createFishSlice: StateCreator<State, [], [], FishSlice> = (set) => ({
fishes: 0,
addFish: () => set((s) => ({ fishes: s.fishes + 1 })),
});
const useBaseStore = create<State>()((...args) => ({
...createBearSlice(...args),
...createFishSlice(...args),
}));
export const useStore = createSelectors(useBaseStore);Inside a component, I checked the combined example with Zustand 5.0.15 and TypeScript 7.0.2: the generated hooks preserve number/function types, reject unknown keys, and a rendered component updated correctly when either slice's action ran. The slice guide covers composing the slices; apply middleware to the combined store if you add it. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Hello!
Congratulations on this project. It's clear and useful! 🥇
Is it possible to combine autogenerated selectors with slices? I can't find any documentation on that, so perhaps it isn't possible.
It would be a great idea to include demonstrations in the documentation, if possible. And with TS...
Many thanks! 🙏
All reactions