Skip to content

Commit 3ccb729

Browse files
committed
Add storing user in localstorage
1 parent 34bca1f commit 3ccb729

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

src/reducers/auth.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,31 @@
11
import { LOGIN, LOGOUT, REDIRECT } from '../actions';
22

3+
const userString = window.localStorage.getItem('user');
4+
let user = {};
5+
try {
6+
user = JSON.parse(userString) || {};
7+
} catch (err) {
8+
console.log('User not found');
9+
}
10+
311
const initialState = {
4-
username: '',
5-
loggedIn: false,
12+
username: user.username || '',
13+
loggedIn: user.loggedIn || false,
614
redirectUrl: '',
715
};
816

917
const authReducer = (state = initialState, action) => {
1018
switch (action.type) {
1119
case LOGIN:
12-
return Object.assign({}, state, { loggedIn: true, username: action.payload });
20+
const newLoginState = Object.assign({}, state, { loggedIn: true, username: action.payload });
21+
const loginUser = { username: newLoginState.username, loggedIn: newLoginState.loggedIn };
22+
window.localStorage.setItem('user', JSON.stringify(loginUser));
23+
return newLoginState;
1324
case LOGOUT:
14-
return Object.assign({}, state, { loggedIn: false });
25+
const newLogoutState = Object.assign({}, state, { loggedIn: false });
26+
const logoutUser = { username: newLogoutState.username, loggedIn: newLogoutState.loggedIn };
27+
window.localStorage.setItem('user', JSON.stringify(logoutUser));
28+
return newLogoutState;
1529
case REDIRECT:
1630
return Object.assign({}, state, { redirectUrl: action.payload });
1731
default:

0 commit comments

Comments
 (0)