Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created June 11, 2025 14:05
Show Gist options
  • Save sunmeat/38a6c542cb660f6e5c8113b1f1010318 to your computer and use it in GitHub Desktop.
Save sunmeat/38a6c542cb660f6e5c8113b1f1010318 to your computer and use it in GitHub Desktop.
аутентификация на редаксе
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useSelector, useDispatch } from 'react-redux';
import { useState } from 'react';
// слайс для аутентификации
const authSlice = createSlice({
name: 'auth',
initialState: {
user: null,
isAuthenticated: false,
error: null,
},
reducers: {
login: (state, action) => {
state.user = action.payload;
state.isAuthenticated = true;
state.error = null;
},
logout: (state) => {
state.user = null;
state.isAuthenticated = false;
state.error = null;
},
setError: (state, action) => {
state.error = action.payload;
},
},
});
// действия
const { login, logout, setError } = authSlice.actions;
// создание хранилища
const store = configureStore({
reducer: {
auth: authSlice.reducer,
},
});
// компонент аутентификации
function AuthComponent() {
const [username, setUsername] = useState('');
const { user, isAuthenticated, error } = useSelector((state) => state.auth);
const dispatch = useDispatch();
// обработка входа
const handleLogin = () => {
if (username.trim()) {
dispatch(login({ username }));
} else {
dispatch(setError('Введите имя пользователя'));
}
};
// обработка выхода
const handleLogout = () => {
dispatch(logout());
};
return (
<div>
{isAuthenticated ? (
<div>
<h1>Добро пожаловать, {user.username}!</h1>
<button onClick={handleLogout}>Выйти</button>
</div>
) : (
<div>
<h1>Вход</h1>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Имя пользователя"
/>
<button onClick={handleLogin}>Войти</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</div>
)}
</div>
);
}
// обертка приложения
function App() {
return (
<Provider store={store}>
<AuthComponent />
</Provider>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment