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'; import PropTypes from 'prop-types';
const initialState = { // Функция для сохранения состояния user в localStorage
user: null, 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) => { const AuthReducer = (state, action) => {
switch (action.type) { switch (action.type) {
case 'LOGIN': case 'LOGIN':
case 'REGISTER': case 'REGISTER':
saveToLocalstorage(action.payload);
return { return {
...state, ...state,
user: action.payload, user: action.payload,
}; };
case 'LOGOUT': case 'LOGOUT':
saveToLocalstorage(null);
return { return {
...state, ...state,
user: null, user: null,
@ -26,7 +42,18 @@ const AuthReducer = (state, action) => {
export const AuthContext = createContext(); export const AuthContext = createContext();
export const AuthProvider = ({ children }) => { 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 ( return (
<AuthContext.Provider value={{ state, dispatch }}> <AuthContext.Provider value={{ state, dispatch }}>