diff --git a/Lab5/Bookfill/src/components/logins/context/AuthContex.jsx b/Lab5/Bookfill/src/components/logins/context/AuthContex.jsx index 0bde443..dfd5231 100644 --- a/Lab5/Bookfill/src/components/logins/context/AuthContex.jsx +++ b/Lab5/Bookfill/src/components/logins/context/AuthContex.jsx @@ -1,19 +1,35 @@ -import { createContext, useReducer } from 'react'; +import { createContext, useReducer, useEffect } from 'react'; import PropTypes from 'prop-types'; -const initialState = { - user: null, +// Функция для сохранения состояния user в localStorage +const saveToLocalstorage = (user) => { + if (user) { + localStorage.setItem('authState', JSON.stringify(user)); + } else { + localStorage.removeItem('authState'); + } +}; + +// Функция для восстановления состояния user из localStorage +const getInitialState = () => { + const userStorage = localStorage.getItem('authState'); + if (userStorage) { + return { user: JSON.parse(userStorage) }; + } + return { user: null }; }; const AuthReducer = (state, action) => { switch (action.type) { case 'LOGIN': case 'REGISTER': + saveToLocalstorage(action.payload); return { ...state, user: action.payload, }; case 'LOGOUT': + saveToLocalstorage(null); return { ...state, user: null, @@ -26,7 +42,18 @@ const AuthReducer = (state, action) => { export const AuthContext = createContext(); export const AuthProvider = ({ children }) => { - const [state, dispatch] = useReducer(AuthReducer, initialState); + const [state, dispatch] = useReducer(AuthReducer, getInitialState, getInitialState); + + // При инициализации компонента проверим localStorage + useEffect(() => { + const user = localStorage.getItem('authState'); + if (user) { + dispatch({ + type: 'LOGIN', + payload: JSON.parse(user), + }); + } + }, []); return (