zustandjs / zustand-slices

A slice utility for Zustand
MIT License
137 stars 6 forks source link

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

Closed vcardins closed 1 day ago

vcardins commented 2 days ago

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,
        }),
    },
});
dai-shi commented 2 days ago

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. https://github.com/zustandjs/zustand-slices/blob/4274b6da19ccef882b84543cfb2528e36c26b5fa/examples/03_actions/src/app.tsx#L24-L28

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

vcardins commented 2 days ago

@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 ?

dai-shi commented 2 days ago

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.

vcardins commented 1 day ago

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