Zustand: reset multiple stores

726 views Asked by At

I created several stores, they work, everything is ok.

Then, when I log out, I call resetAllStores, set default values to store. In localStorage I can see the default values.

But if you sign in once again in the application and reload the page, then InitialState will already have the values ​​that I pushed there, having received some data from the API, and when I click on the logout button, I will not set objects with default values ​​in the store.

How to fix it?

import { StoreApi, UseBoundStore, create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

export type Store<T extends unknown> = UseBoundStore<StoreApi<T>>;

const storeResetFns = new Set<() => void>();

export const resetAllStores = () => {
  storeResetFns.forEach(resetFn => {
    resetFn();
  });
};

export const createStore = <T extends unknown>(
  fn: (set: StoreApi<T>['setState'], get: StoreApi<T>['getState'], api: StoreApi<T>) => T,
  persistName: string,
  devToolsName?: string
): Store<T> => {
  const store = create<T>()(
    devtools(persist(fn, { name: persistName }), {
      name: devToolsName || persistName,
      enabled: process.env.NODE_ENV === 'development',
    })
  );
  const initialState = store.getState();

  storeResetFns.add(() => {
    store.setState(initialState, true);
  });

  return store;
};

const initialState = { user: null }

export const useAuth = createStore<AuthState & AuthActions>(
  immer(set => ({
    ...initialState,
  })),
  'auth'
);

When user sign in to the app I set user for example {user: {name: 'TEST NAME'}}. When I click logout button, I set {user: null} after but if I reload page: {user: {name: 'TEST NAME'}}. How to prevent this and always set {user: null}

I have tried this guide But it does not work with page reloading

0

There are 0 answers