index.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import thunk from 'redux-thunk';
  2. import { actionAuthLogin } from '../actions'
  3. import {createStore, combineReducers, applyMiddleware} from 'redux';
  4. function promiseReducer(state = {}, { type, name, status, payload, error }) {
  5. if (type === 'PROMISE') {
  6. return {
  7. ...state,
  8. [name]: { status, payload, error },
  9. }
  10. }
  11. return state
  12. }
  13. const jwtDecode = (token) => {
  14. try {
  15. return JSON.parse(atob(token.split('.')[1]))
  16. } catch (e) {
  17. return null
  18. }
  19. }
  20. function authReducer(state, { type, token }) {
  21. if (state === undefined && localStorage.authToken) {
  22. token = localStorage.authToken
  23. type = 'AUTH_LOGIN'
  24. }
  25. if (type === 'AUTH_LOGIN') {
  26. if (jwtDecode(token)) {
  27. localStorage.authToken = token
  28. return { token, payload: jwtDecode(token) }
  29. }
  30. }
  31. if (type === 'AUTH_LOGOUT') {
  32. localStorage.authToken = ''
  33. return {}
  34. }
  35. return state || {}
  36. }
  37. export const store = createStore(
  38. combineReducers({
  39. promise: promiseReducer,
  40. auth: authReducer,
  41. }),
  42. applyMiddleware(thunk),
  43. )