authReducer.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { useHistory } from 'react-router-dom';
  2. // const jwtDecode = token =>{
  3. // try{
  4. // let payload = JSON.parse(atob(token.split('.')[1]));
  5. // return payload;
  6. // } catch(e){
  7. // }
  8. // }
  9. export const authReducer = function(state, {type, token, user}) {
  10. if (state === undefined) {
  11. if(localStorage.authToken) {
  12. type = "AUTH_LOGIN";
  13. token = localStorage.authToken;
  14. user = JSON.parse(localStorage.user);
  15. } else {
  16. type = "AUTH_LOGOUT";
  17. };
  18. };
  19. if (type === "AUTH_LOGIN") {
  20. localStorage.authToken = token;
  21. localStorage.user = JSON.stringify(user);
  22. return {
  23. token: token,
  24. user: user
  25. }
  26. };
  27. if (type === "AUTH_LOGOUT") {
  28. localStorage.removeItem("authToken");
  29. return {};
  30. };
  31. return state || {};
  32. };
  33. export const actionAuthLogin = (token, user) => ({type: "AUTH_LOGIN", token, user});
  34. export const actionAuthLogout = () => ({type: "AUTH_LOGOUT"});