This commit is contained in:
GokaPek 2024-01-07 20:14:21 +04:00
parent 933c8157cf
commit 090fb8c38b

View File

@ -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 (
<AuthContext.Provider value={{ state, dispatch }}>