-
Hi, Currently I try to switch from redux-toolkit to zustand and I'm a little bit stuck because I want to have complete typescript and immer-Middleware support for all slices. I create my store like so: import create, { GetState, SetState } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import { devtools } from 'zustand/middleware';
import { createArticleSlice } from './articleSlice';
export type StoreSlice<T extends object, E extends object = T> = (
set: (
nextStateOrUpdater: object | ((state: E extends T ? E : E & T) => void),
shouldReplace?: boolean | undefined,
actionType?:
| string
| {
type: unknown;
}
| undefined
) => void,
get: GetState<E extends T ? E : E & T>
) => T;
const createRootSlice = (set: SetState<any>, get: GetState<any>) => ({
article: createArticleSlice(set, get),
});
export const useStore = create(devtools(immer(createRootSlice), { name: 'ZustandStore' })); Slice: import { IPageableRequestData } from '@/models/article';
import { StoreSlice } from './store';
interface ArticleSlice {
newVisiblePageLoading: boolean;
pageRequestData: Omit<IPageableRequestData, 'limit' | 'from'> | undefined;
setPagerequestData: (data: Omit<IPageableRequestData, 'limit' | 'from'>) => void;
setNewPageDataLoading: (data: boolean) => void;
}
export const createArticleSlice: StoreSlice<ArticleSlice> = (set) => ({
pageRequestData: undefined,
newVisiblePageLoading: false,
setPagerequestData: (data: Omit<IPageableRequestData, 'limit' | 'from'>) =>
set((state) => {
state.article.pageRequestData = data;
}),
setNewPageDataLoading: (data) =>
set((state) => {
state.article.newVisiblePageLoading = data;
}),
}); Using it inside of a component is perfect just how I would like to have it, e.g. I need to write "state.article.variableName" but I only want to write "state.variableName", just like in redux-toolkit. The types in the slice are not working because state(inside of the set-function) thinks it should be of type ArticleSlice but it actually is of type "{ article: ArticleSlice }" Is this what I try to achieve possible to do? And is it possible to split the actions from the state ? I saw this but it's not fully the same to what i try to achieve. Thanks in advance and I hope I expressed well, since English is not my native language :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
#178 is the discussion about namespacing, and it's a field for third-party libraries.
What do you mean by this? |
Beta Was this translation helpful? Give feedback.
#178 is the discussion about namespacing, and it's a field for third-party libraries.
What do you mean by this?