zustandjs / zustand-slices

A slice utility for Zustand

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I have access to the setState method within an action?

vcardins opened this issue · comments

I'd like to be able to do reuse getBaseActions. How can I access set from within createSlice?

export const datasetSlice = createSlice<'dataset', DatasetState, DatasetAction>({
	name: 'dataset',
	value: {
		...baseState,
		filters: defaultFilters,
	},
	actions: {
		// ...getBaseActions(set, get),
		updateFilters: (filters: ISearchFilterProps) => (_prevValue: DatasetState) => ({
			...baseState,
			filters,
		}),
	},
});

You can't. The rationale here is that slices are isolated, and a slice can't know other slices.
We have withActions for inter-slice logic.

withActions(withSlices(countSlice, textSlice), {
setCountWithTextLength: () => (state) => {
state['count/set'](state.text.length);
},
}),

Let me know if it works for your case or not.


If it doesn't, I guess your case would fit better with the original slicing pattern without this library.
https://github.com/pmndrs/zustand/blob/f8403fc57928da5afe8894a23b1fb3f901658dcf/docs/guides/slices-pattern.md

@dai-shi Thanks for the prompt response. I'm actually testing different slicing pattern. I've played with the one your suggested as well as zustand-x which has been the "winner" so far.
Btw, any comment on Zustand-x ?

To me, zustand-x is an opinionated wrapper library around zustand and others.

zustand-slices (also opinionated) is a util library to be used with zustand (unopinionated). Just creating so-called createState factory.

Sounds good, @dai-shi! I'm happy with your responses.