Skip to content

Commit fb2b5b4

Browse files
committed
Fix error dispatch actions auths
1 parent 1e10316 commit fb2b5b4

20 files changed

+111
-129
lines changed

package.json

-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
"@types/styled-components": "^5.1.4",
2020
"antd": "^4.9.2",
2121
"concurrently": "^5.3.0",
22-
"immer": "^8.0.0",
2322
"json-server": "^0.16.3",
2423
"react": "^17.0.1",
2524
"react-dom": "^17.0.1",

server/db/db.json

+6
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@
1717
"username": "alan",
1818
"email": "[email protected]",
1919
"password": "123456"
20+
},
21+
{
22+
"id": "38550566-e1c6-40c2-a616-8ea74189f677",
23+
"username": "felix",
24+
"email": "[email protected]",
25+
"password": "123456"
2026
}
2127
],
2228
"products": []

src/@types/actions.d.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
interface ActionRedux {
2-
types: string;
2+
type: string;
33
payload?: any;
44
}

src/@types/user.d.ts

+5
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,8 @@ interface IUser {
1818
email?: string;
1919
password: string;
2020
}
21+
22+
interface DispatchAuth {
23+
type: string;
24+
payload?: any;
25+
}

src/App/App.actions.ts

-9
This file was deleted.

src/App/App.constants.ts

-2
This file was deleted.

src/App/App.reducer.ts

-26
This file was deleted.

src/App/App.tsx

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,30 @@
11
import React, { useEffect } from 'react';
2+
import { connect, ConnectedProps } from 'react-redux';
23
import { loadUser, logout } from 'src/components/Auth/Auth.thunks';
34
import { Routes } from 'src/routes';
45

5-
function App() {
6+
const mapStateToProps = () => ({});
7+
const mapDispatchToProps = {
8+
loadUser,
9+
logout,
10+
};
11+
const connector = connect(mapStateToProps, mapDispatchToProps);
12+
interface Props extends ConnectedProps<typeof connector> {}
13+
14+
const _App = (props: Props) => {
15+
useEffect(() => {
16+
const { loadUser, logout } = props;
17+
// check for token in LS
18+
if (localStorage.token) {
19+
loadUser();
20+
}
21+
22+
// log user out from all tabs if they log out in one tab
23+
window.addEventListener('storage', () => {
24+
if (!localStorage.token) logout();
25+
});
26+
}, []);
627
return <Routes />;
7-
}
28+
};
829

9-
export default App;
30+
export const App = connector(_App);

src/components/Auth/Auth.actions.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import * as types from './Auth.constants';
22

3-
export const loginRequested = () => ({
4-
type: types.LOGIN_REQUESTED,
5-
});
6-
73
export const loginSuccess = (payload: IUser) => ({
84
type: types.LOGIN_SUCCESS,
95
payload,
@@ -22,7 +18,7 @@ export const authError = () => ({
2218
type: types.AUTH_ERROR,
2319
});
2420

25-
export const logout = () => ({
21+
export const logoutSuccess = () => ({
2622
type: types.LOGOUT,
2723
});
2824

src/components/Auth/Auth.constants.ts

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
export const LOGIN_SUCCESS = 'views/auth/LOGIN_SUCCESS';
22
export const LOGIN_FAILED = 'views/auth/LOGIN_FAILED';
3-
export const LOGIN_REQUESTED = 'views/auth/LOGIN_REQUESTED';
43
export const USER_LOADED = 'views/auth/USER_LOADED';
54
export const AUTH_ERROR = 'views/auth/AUTH_ERROR';
65
export const LOGOUT = 'views/auth/LOGOUT';

src/components/Auth/Auth.reducers.ts

+35-32
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import * as types from './Auth.constants';
2-
import produce from 'immer';
3-
import { WritableDraft } from 'immer/dist/internal';
42

53
let userType: IUser = {
64
id: '',
@@ -15,34 +13,39 @@ const initialState = {
1513
user: userType,
1614
};
1715

18-
export const authReducer = (
19-
state = initialState,
20-
action: { type: any; payload: WritableDraft<IUser> },
21-
) =>
22-
produce(state, draft => {
23-
switch (action.type) {
24-
case types.USER_LOADED:
25-
draft.isAuthenticated = true;
26-
draft.loading = false;
27-
draft.user = action.payload;
28-
break;
29-
case types.LOGIN_SUCCESS:
30-
case types.REGISTER_SUCCESS:
31-
localStorage.setItem('token', draft.user.id);
32-
draft.loading = false;
33-
draft.isAuthenticated = true;
34-
break;
35-
case types.LOGIN_FAILED:
36-
case types.AUTH_ERROR:
37-
case types.LOGOUT:
38-
case types.REGISTER_FAILED:
39-
localStorage.removeItem('token');
40-
draft.loading = false;
41-
draft.isAuthenticated = false;
42-
draft.token = null;
43-
break;
16+
export const authReducer = (state = initialState, action: ActionRedux) => {
17+
const { type, payload } = action;
18+
switch (type) {
19+
case types.USER_LOADED:
20+
return {
21+
...state,
22+
isAuthenticated: true,
23+
loading: false,
24+
token: payload.id,
25+
user: payload.user,
26+
};
27+
case types.LOGIN_SUCCESS:
28+
case types.REGISTER_SUCCESS:
29+
localStorage.setItem('token', payload.id);
30+
return {
31+
...state,
32+
...payload,
33+
isAuthenticated: true,
34+
loading: false,
35+
};
36+
case types.LOGIN_FAILED:
37+
case types.AUTH_ERROR:
38+
case types.LOGOUT:
39+
case types.REGISTER_FAILED:
40+
localStorage.removeItem('token');
41+
return {
42+
...state,
43+
token: null,
44+
isAuthenticated: false,
45+
loading: false,
46+
};
4447

45-
default:
46-
return state;
47-
}
48-
});
48+
default:
49+
return state;
50+
}
51+
};

src/components/Auth/Auth.thunks.ts

+16-7
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,40 @@ import { v4 as uuid } from 'uuid';
55

66
export const loadUser = () => async dispatch => {
77
const tokenId = localStorage.getItem('token');
8+
console.log('Load user running!');
89
if (!tokenId) {
910
return dispatch(actions.authError);
1011
}
1112
try {
1213
const res = await axios.get(`${URL.baseAPIUrl}/api/users/${tokenId}`);
14+
console.log('Response', res);
15+
console.log('Hey loadUser function triggered');
1316
if (res) {
14-
return dispatch(actions.userLoaded(res));
17+
return dispatch(actions.userLoaded(res.data));
1518
}
1619
dispatch(actions.authError);
1720
} catch (error) {
21+
console.log('Some error loadUser running', error);
1822
return dispatch(actions.authError);
1923
}
2024
};
2125

2226
export const login = (payload: ReqLogin) => async dispatch => {
2327
const { username, password } = payload;
2428
try {
25-
let allUsers: IUser[] = [];
26-
allUsers = await axios.get(`${URL.baseAPIUrl}/api/users`);
29+
const res = await axios.get(`${URL.baseAPIUrl}/api/users`);
30+
const allUsers = res.data;
31+
2732
let user = allUsers.filter(x => x.username === username)[0];
33+
console.log('user', user);
2834
if (user && user.password === password) {
2935
dispatch(actions.loginSuccess(user));
30-
loadUser();
36+
dispatch(loadUser());
37+
return;
38+
} else {
39+
console.log('Invalid credentials');
40+
return dispatch(actions.loginFailed);
3141
}
32-
dispatch(actions.loginFailed);
3342
} catch (error) {
3443
return dispatch(actions.loginFailed);
3544
}
@@ -44,11 +53,11 @@ export const register = (payload: ReqLogin) => async dispatch => {
4453
console.log('Resgister success', newUser);
4554
const all = await axios.get(`${URL.baseAPIUrl}/api/users`);
4655
console.log('All users', all);
47-
loadUser();
56+
dispatch(loadUser());
4857
} catch (error) {
4958
return dispatch(actions.registerFailed);
5059
}
5160
};
5261
export const logout = () => async dispatch => {
53-
return dispatch(actions.logout);
62+
return dispatch(actions.logoutSuccess);
5463
};

src/components/Auth/Login.tsx

+10-13
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ import { login } from './Auth.thunks';
77
import { PATH } from 'src/constants/paths';
88

99
const mapStateToProps = (state: AppState) => ({
10-
loading: state.auth.loading,
11-
isAuthenticated: state.app.isAuthenticated,
10+
isAuthenticated: state.auth.isAuthenticated,
1211
});
1312
const mapDispatchToProps = {
1413
login,
@@ -19,21 +18,19 @@ interface Props extends ConnectedProps<typeof connector> {}
1918
const _Login = (props: Props) => {
2019
// eslint-disable-next-line
2120
const [error, setError] = useState('');
22-
const { login, loading } = props;
21+
const { login } = props;
2322
const history = useHistory();
2423

2524
const onFinish = async formData => {
2625
const { username, password } = formData;
27-
if (!loading) {
28-
const payload = { username, password };
29-
try {
30-
await login(payload);
31-
message.success('Login successfully');
32-
history.push(PATH.HOME);
33-
} catch (error) {
34-
message.error(error.message);
35-
setError(error.payload.message);
36-
}
26+
const payload = { username, password };
27+
try {
28+
await login(payload);
29+
message.success('Login successfully');
30+
history.push(PATH.HOME);
31+
} catch (error) {
32+
message.error(error.message);
33+
setError(error.payload.message);
3734
}
3835
};
3936

src/components/Auth/Register.tsx

+8-11
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,7 @@ import { register } from './Auth.thunks';
77
import { PATH } from 'src/constants/paths';
88

99
const mapStateToProps = (state: AppState) => ({
10-
loading: state.auth.loading,
11-
isAuthenticated: state.app.isAuthenticated,
10+
isAuthenticated: state.auth.isAuthenticated,
1211
});
1312
const mapDispatchToProps = {
1413
register,
@@ -19,18 +18,16 @@ interface Props extends ConnectedProps<typeof connector> {}
1918
const _Register = (props: Props) => {
2019
// eslint-disable-next-line
2120
const [error, setError] = useState('');
22-
const { register, loading } = props;
21+
const { register } = props;
2322
const history = useHistory();
2423

2524
const onFinish = async formData => {
26-
if (!loading) {
27-
try {
28-
await register(formData);
29-
message.success('Register successfully');
30-
history.push(PATH.HOME);
31-
} catch (error) {
32-
setError(error.payload.message);
33-
}
25+
try {
26+
await register(formData);
27+
message.success('Register successfully');
28+
history.push(PATH.HOME);
29+
} catch (error) {
30+
setError(error.payload.message);
3431
}
3532
};
3633
const onFinishFailed = errorInfo => {

src/components/Header/RightMenu.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const { useBreakpoint } = Grid;
1010

1111
const mapStateToProps = (state: AppState) => ({
1212
loading: state.auth.loading,
13-
isAuthenticated: state.app.isAuthenticated,
13+
isAuthenticated: state.auth.isAuthenticated,
1414
});
1515
const mapDispatchToProps = {
1616
logout,

src/components/Home/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { Link } from 'react-router-dom';
66

77
const mapStateToProps = (state: AppState) => ({
88
loading: state.auth.loading,
9-
isAuthenticated: state.app.isAuthenticated,
9+
isAuthenticated: state.auth.isAuthenticated,
1010
});
1111
const mapDispatchToProps = {};
1212

src/index.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React from 'react';
22
import ReactDOM from 'react-dom';
33
import 'src/assets/scss/index.scss';
44
import 'antd/dist/antd.css';
5-
import App from './App/App';
5+
import { App } from './App/App';
66
import reportWebVitals from './reportWebVitals';
77
import { Provider } from 'react-redux';
88
import { store } from './store';

src/reducer/index.ts

-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import { combineReducers } from 'redux';
2-
import { AppReducer } from 'src/App/App.reducer';
32
import { authReducer } from 'src/components/Auth/Auth.reducers';
43
// import { ProductListReducer } from "src/pages/Product/ProductList/ProductList.reducer"
54
// import { productItemReducer } from "src/pages/Product/ProductItem/ProductItem.reducer"
65

76
export const RootReducer = combineReducers({
8-
app: AppReducer,
97
auth: authReducer,
108
});

0 commit comments

Comments
 (0)