@luxurypluxury

Почему при логине в localstorage сохраняется false?

При сабмите в форме логина в localstorage должен ставится true, но в localstorage ставится false и при последующей перезагрузке страницы профиль пропадает и снова появляется авторизация.
Почему так?
Вот редакс слайс:
import { createSlice, PayloadAction } from "@reduxjs/toolkit"
import { AuthSliceState } from "./types";
import { getAuthFromLS } from "@/utils/getAuthFromLS";

const initialState: AuthSliceState = {
    isAuth: getAuthFromLS(),
}

export const AuthSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setIsAuth(state, action: PayloadAction<boolean>) {
            state.isAuth = action.payload;
        }
    }
})

export const { setIsAuth } = AuthSlice.actions;

export default AuthSlice.reducer;


Вот функция получения значения с localstorage:
export const getAuthFromLS = (): boolean => {
    const data = localStorage.getItem('auth');
    const auth = data ? JSON.parse(data) : [];

    return auth;
}


Вот сабмит в авторизации:
const dispatch = useDispatch();
    const isAuth = useSelector(isAuthSelector);
    const isMounted = useRef(false);
    const navigate = useNavigate();

    useEffect(() => {
        if (isMounted.current) {
            const json = JSON.stringify(isAuth);
            localStorage.setItem('auth', json);
        }
        isMounted.current = true;
    }, [isAuth]);

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        dispatch(setIsAuth(true));
        navigate('/');
    }


Вот logout:
useEffect(() => {
        if (isMounted.current) {
            const json = JSON.stringify(isAuth);
            localStorage.setItem('auth', json);
        }
        isMounted.current = true;
    }, [isAuth]);

    const handleLogout = () => {
        if (confirm('Are you sure you want to exit?')) {
            dispatch(setIsAuth(false));
            navigate('/');
        }
    }
  • Вопрос задан
  • 102 просмотра
Пригласить эксперта
Ответы на вопрос 1
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(),
    },
  },
});
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы