Skip to content

Instantly share code, notes, and snippets.

@kjmczk
Created July 23, 2019 08:33
Show Gist options
  • Save kjmczk/64f302546e4cd38ff922cf5d59192b8e to your computer and use it in GitHub Desktop.
Save kjmczk/64f302546e4cd38ff922cf5d59192b8e to your computer and use it in GitHub Desktop.
#16 User Auth with Knox - Blog
// frontend/src/reducers/auth.js
import {
USER_LOADING,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL
} from '../actions/types';
const initialState = {
isLoading: false,
isAuthenticated: null,
user: null,
token: localStorage.getItem('token')
};
export default function(state = initialState, action) {
switch (action.type) {
case USER_LOADING:
return {
...state,
isLoading: true
};
case USER_LOADED:
return {
...state,
isLoading: false,
isAuthenticated: true,
user: action.payload
};
case LOGIN_SUCCESS:
localStorage.setItem('token', action.payload.token);
return {
...state,
isLoading: false,
isAuthenticated: true,
...action.payload
};
case AUTH_ERROR:
case LOGIN_FAIL:
localStorage.removeItem('token');
return {
...state,
isLoading: false,
isAuthenticated: false,
user: null,
token: null
};
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment