Skip to content

Commit

Permalink
auth slice
Browse files Browse the repository at this point in the history
  • Loading branch information
KaratSergio committed Jan 26, 2024
1 parent 39dc38e commit 12df7c9
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/components/Routes/AuthRoute.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import {
selectIsLoggedIn,
selectIsRefreshing,
} from '../../redux/auth/selectors';

const AuthRoute = ({ component: Component, redirectTo = '/' }) => {
const isLoggedIn = useSelector(selectIsLoggedIn);
const isRefreshing = useSelector(selectIsRefreshing);

const shouldRedirect = !isLoggedIn && !isRefreshing;
return shouldRedirect ? <Navigate to={redirectTo} /> : <Component />;
};

export default AuthRoute;
11 changes: 11 additions & 0 deletions src/components/Routes/GuestRoute.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Navigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { selectIsLoggedIn } from '../../redux/auth/selectors';

const GuestRoute = ({ component: Component, redirectTo = '/' }) => {
const isLoggedIn = useSelector(selectIsLoggedIn);

return isLoggedIn ? <Navigate to={redirectTo} /> : <Component />;
};

export default GuestRoute;
46 changes: 46 additions & 0 deletions src/redux/auth/slice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { createSlice } from '@reduxjs/toolkit';
import { register, logIn, logOut, refreshUser } from './operations';

const initialState = {
user: { name: null, email: null },
token: null,
isLoggedIn: false,
isRefreshing: false,
};

const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {},
extraReducers: builder => {
builder
.addCase(register.fulfilled, (state, action) => {
state.user = action.payload.user;
state.token = action.payload.token;
state.isLoggedIn = true;
})
.addCase(logIn.fulfilled, (state, action) => {
state.user = action.payload.user;
state.token = action.payload.token;
state.isLoggedIn = true;
})
.addCase(logOut.fulfilled, (state, action) => {
state.user = action.payload.user;
state.token = action.payload.token;
state.isLoggedIn = false;
})
.addCase(refreshUser.pending, state => {
state.isRefreshing = true;
})
.addCase(refreshUser.fulfilled, (state, action) => {
state.user = action.payload;
state.isLoggedIn = true;
state.isRefreshing = false;
})
.addCase(refreshUser.rejected, state => {
state.isRefreshing = false;
});
},
});

export const authReducer = authSlice.reducer;

0 comments on commit 12df7c9

Please sign in to comment.