Search code examples
typescriptstate-managementzustand

Adding persist middleware to zustand store


I want to add a persist middleware to my useGlobalStore. I want to handle there (set and get) data for sessions store. I look through documentation but could not find an answer how to combine together my create and persist functions.

Here is my useGlobalStore:

interface Store extends HeatMapState, WeeklyOverviewState, MonthlyOverviewState, GlobalState, UserState {}

export const useGlobalStore = create<Store>(
    devtools((set, get, api) => ({
        ...heatMapSlice(set as SetState<HeatMapState>, get as GetState<HeatMapState>, api as StoreApi<HeatMapState>),
        ...weeklyOverviewSlice(
            set as SetState<WeeklyOverviewState>,
            get as GetState<WeeklyOverviewState>,
            api as StoreApi<WeeklyOverviewState>,
        ),
        ...monthlyOverviewSlice(
            set as SetState<MonthlyOverviewState>,
            get as GetState<MonthlyOverviewState>,
            api as StoreApi<MonthlyOverviewState>,
        ),
        ...globalStateSlice(set as SetState<GlobalState>, get as GetState<GlobalState>, api as StoreApi<GlobalState>),
        ...userStateSlice(set as SetState<UserState>, get as GetState<UserState>, api as StoreApi<UserState>),
    })),
) as UseBoundStore<Store, StoreApi<Store>>

Solution

  • https://github.com/pmndrs/zustand#middleware

    you can find it under How to pipe middlewares

    const createStore = pipe(persistor, devtools, create)
    create<Store>(....store )
    

    this should work for your case