Skip to content

Commit

Permalink
Merge pull request #11 from 001elijah/auth
Browse files Browse the repository at this point in the history
Auth
  • Loading branch information
001elijah authored Jun 19, 2023
2 parents c4780c0 + fdb3aca commit e098d12
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 20 deletions.
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"clsx": "^1.2.1",
"formik": "^2.4.2",
"modern-normalize": "^2.0.0",
"notiflix": "^3.2.6",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-redux": "^8.1.0",
Expand Down
16 changes: 14 additions & 2 deletions src/pages/HomePage.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
import React from 'react';
import { useDispatch } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import { logoutUser } from 'redux/Auth/authOperations';
import { themeChangeUser } from 'redux/Auth/authOperations';
import { selectorTheme } from 'redux/Auth/authSelectors';

export const HomePage = () => {
const theme = useSelector(selectorTheme) || "";
const dispatch = useDispatch();

const handleChange = e => {
dispatch(themeChangeUser(e.target.value));
};

return (
<div>
<select name="priority" value={theme} onChange={handleChange}>
<option value="light">Light</option>
<option value="dark">Dark</option>
<option value="colorful">Colorful</option>
</select>
<button onClick={() => dispatch(logoutUser())}>Log logOut</button>
</div>
);
Expand Down
39 changes: 37 additions & 2 deletions src/redux/Auth/authOperations.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { Notify } from 'notiflix';

import { createAsyncThunk } from '@reduxjs/toolkit';
import { logOut } from './authSlice';

Expand All @@ -6,15 +8,27 @@ import {
loginUserApi,
currentUserApi,
logoutUserApi,
themeChangeUserApi,
// themeChangeUserApi
} from 'services/backendAPI';

export const registerUser = createAsyncThunk(
'auth/register',
async (dataUser, { rejectWithValue }) => {
try {
const data = await registerUserApi(dataUser);
Notify.success('Welcome');
return data;
} catch (error) {
const { status } = error.response.request;

if (status === 409) {
Notify.failure('Email already exists');
} else if (status === 400) {
Notify.failure(`Error`);
} else if (status === 500) {
Notify.failure('Server error');
}
return rejectWithValue(error.message);
}
},
Expand All @@ -25,8 +39,18 @@ export const loginUser = createAsyncThunk(
async (dataUser, { rejectWithValue }) => {
try {
const userData = await loginUserApi(dataUser);
Notify.success('Welcome');
return userData;
} catch (error) {
const { status } = error.response.request;
if (status === 401) {
Notify.failure('Email or password is wrong');
} else if (status === 400) {
Notify.failure(`Error`);
} else if (status === 500) {
Notify.failure('Server error');
}

return rejectWithValue(error.message);
}
},
Expand Down Expand Up @@ -56,8 +80,7 @@ export const currentUser = createAsyncThunk(

export const logoutUser = createAsyncThunk(
'auth/logout',
async (_, { getState, rejectWithValue }) => {
const { token } = getState().auth;
async (token, { rejectWithValue }) => {
try {
await logoutUserApi(token);
return null;
Expand All @@ -66,3 +89,15 @@ export const logoutUser = createAsyncThunk(
}
},
);

export const themeChangeUser = createAsyncThunk(
'auth/themeChange',
async (theme, { rejectWithValue }) => {
try {
await themeChangeUserApi({ theme });
return theme;
} catch (error) {
return rejectWithValue(error.message);
}
},
);
14 changes: 7 additions & 7 deletions src/redux/Auth/authSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
loginUser,
currentUser,
logoutUser,
themeChangeUser,
} from './authOperations';

const authSlice = createSlice({
Expand All @@ -15,7 +16,6 @@ const authSlice = createSlice({
email: null,
theme: null,
avatarUrl: null,
isLoading: false,
error: null,
},
reducers: {
Expand All @@ -27,7 +27,6 @@ const authSlice = createSlice({
email: null,
theme: null,
avatarUrl: null,
isLoading: false,
error: null,
};
},
Expand All @@ -38,18 +37,21 @@ const authSlice = createSlice({
return {
...state,
...payload,
isAuth: true,
};
})
.addCase(loginUser.fulfilled, (state, { payload }) => {
return {
...state,
...payload,
isAuth: true,
};
})
.addCase(currentUser.fulfilled, (state, { payload }) => {
return {
...state,
...payload,
isAuth: true,
};
})
.addCase(logoutUser.fulfilled, () => {
Expand All @@ -60,32 +62,30 @@ const authSlice = createSlice({
email: null,
theme: null,
avatarUrl: null,
isLoading: false,
error: null,
};
})
.addCase(themeChangeUser.fulfilled, (state, { payload }) => {
state.theme = payload;
})
.addMatcher(
action =>
action.type.startsWith('auth') && action.type.endsWith('/fulfilled'),
state => {
state.isAuth = true;
state.isLoading = false;
state.error = null;
},
)
.addMatcher(
action =>
action.type.startsWith('auth') && action.type.endsWith('/pending'),
state => {
state.isLoading = true;
state.error = null;
},
)
.addMatcher(
action =>
action.type.startsWith('auth') && action.type.endsWith('/rejected'),
(state, { payload }) => {
state.isLoading = false;
state.error = payload;
},
);
Expand Down
1 change: 1 addition & 0 deletions src/redux/Loader/loaderSelectors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const selectorIsLoading = state => state.isLoading;
21 changes: 21 additions & 0 deletions src/redux/Loader/loaderSlice.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { createSlice } from '@reduxjs/toolkit';

const loaderSlice = createSlice({
name: 'loader',
initialState: false,
extraReducers: builder => {
builder
.addMatcher(
action => action.type.endsWith('/pending'),
() => true,
)
.addMatcher(
action =>
action.type.endsWith('/fulfilled') ||
action.type.endsWith('/rejected'),
() => false,
);
},
});

export default loaderSlice.reducer;
2 changes: 2 additions & 0 deletions src/redux/store.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { configureStore } from '@reduxjs/toolkit';
import authReducer from './Auth/authSlice';
import loaderReducer from './Loader/loaderSlice';

import {
persistStore,
Expand All @@ -24,6 +25,7 @@ const persistedAuthReducer = persistReducer(authPersistConfig, authReducer);
export const store = configureStore({
reducer: {
auth: persistedAuthReducer,
isLoading: loaderReducer,
},
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
Expand Down
21 changes: 12 additions & 9 deletions src/services/backendAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,15 @@ const token = {
};

export const registerUserApi = async userData => {
await axios.post('/register', userData);
const { email, password } = userData;
const login = await loginUserApi({ email, password });
return { ...login };
const { data } = await axios.post('/register', userData);
token.set(data.token);
return { ...data.user, token: data.token };
};

export const loginUserApi = async userData => {
const { data } = await axios.post('/login', userData);
token.set(data.token);
const user = await axios.get('/current');
return { ...user.data, token: data.token };
return { ...data.user, token: data.token };
};

export const currentUserApi = async userToken => {
Expand All @@ -31,8 +29,13 @@ export const currentUserApi = async userToken => {
return data;
};

export const logoutUserApi = async token => {
const { data } = await axios.post('/logout', token);
console.log(data);
export const logoutUserApi = async userToken => {
await axios.post('/logout', userToken);
token.unset();
return null;
};

export const themeChangeUserApi = async theme => {
const { data } = await axios.patch('', theme);
return data;
};

0 comments on commit e098d12

Please sign in to comment.