Задать вопрос
Ответы пользователя по тегу Redux
  • Почему при логине в localstorage сохраняется false?

    meinefinsternis
    @meinefinsternis
    import {
      combineReducers,
      configureStore,
      createListenerMiddleware,
      isAnyOf,
    } from "@reduxjs/toolkit";
    import Auth, { setIsAuth } from "path/to/slice";
    
    const localStorageListenerMiddleware = createListenerMiddleware();
    
    localStorageListenerMiddleware.startListening({
      matcher: isAnyOf(setIsAuth),
      effect: (_, listenerApi) =>
        localStorage.setItem(
          "auth",
          JSON.stringify((listenerApi.getState() as RootState).Auth),
        ),
    });
    
    const re_hydrate_auth = (): boolean => {
      try {
        const userAuthState = localStorage.getItem("auth");
        if (userAuthState) {
          const { isAuth } = JSON.parse(userAuthState) as { isAuth: boolean } - (AuthSliceState);
          return isAuth;
        }
      } catch {
        return false;
      }
      return false;
    };
    
    const reducer = combineReducers({
      Auth,
    });
    
    export const store = configureStore({
      reducer,
      middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(localStorageListenerMiddleware.middleware),
      preloadedState: {
        Auth: {
          isAuth: re_hydrate_auth(),
        },
      },
    });
    Ответ написан
    Комментировать