Zustand "is not a function" error when having 2 persist stage in 1 store

80 Views Asked by At

I have such a setup:

~/states/app_settings.state.ts

const appSettingsState: StateCreator<IAppSettingsState> = (set, get) => ({
  initialTab: 'general',
  setInitialTab: (tab) => {
    set((state) => ({
      ...state,
      initialTab: tab,
    }));
    return true;
  },
});

const useAppSettingsState = persist(appSettingsState, {
  // Configure persist middleware
  name: 'app_settings', // Name of persistent storage
  // getStorage: () => sessionStorage, // Use the browser's session storage
  storage: createJSONStorage(() => localStorage),
  partialize: (state) => ({ initialTab: state.initialTab }),
});

~/states/user.state.ts

const useUserState: StateCreator<IUserState, [], [["zustand/persist", IUserState]]> = persist(
  (set, get) => ({
    user: undefined,
    isLoading: false,
    accessToken: undefined,
    updateAccessToken: (accessToken: string) => set((state: IUserState) => ({ ...state, accessToken })),
    updateUser: (user) => set((state: IUserState) => ({ ...state, user })),
    cleanUserState: () => set({ user: undefined, accessToken: undefined, isLoading: false }),
    startLoading: () => set(_startLoading),
    stopLoading: () => set(_stopLoading),
  }),
  {
    name: 'user',
    version: 1,
  }
);

~/app.store.ts

export const AppStore = create<IStore>()((set, get, api) => ({
  ...useUserState(set, get, api),
  ...useAppSettingsState(set, get, api),
}));

when I want to use setInitialTab function with this setup, I got and error saying : setInitialTab is not a function.

If I update the store by changing the order of useState functions such as:

export const AppStore = create<IStore>()((set, get, api) => ({
  ...useAppSettingsState(set, get, api),
 ...useUserState(set, get, api),
}));

then I got the same error for functions of userState like:

updateAccessToken is not a function.

Isn't that possible to have 2 persist state in 1 store (AppStore) ? Is there a solution except having a separated store for app_settings in my case?

Thanks already!

I tried to have 2 persisting states in 1 store in zustand

0

There are 0 best solutions below