reducers.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // promiseReducer
  2. import { combineReducers } from "redux"
  3. export function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
  4. if (type === 'PROMISE') {
  5. return {
  6. ...state,
  7. [nameOfPromise]: { status, payload, error }
  8. }
  9. }
  10. return state
  11. }
  12. // localStoredReducer
  13. export function localStoredReducer(originalReducer, localStorageKey) {
  14. function wrapper(state, action) {
  15. if (!state) {
  16. try {
  17. return JSON.parse(localStorage[localStorageKey])
  18. }
  19. catch (error) {
  20. }
  21. }
  22. const newState = originalReducer(state, action)
  23. localStorage[localStorageKey] = JSON.stringify(newState)
  24. return newState
  25. }
  26. return wrapper
  27. }
  28. // authReducer
  29. // раскодируем JWT-токен
  30. const jwtDecode = function (token) {
  31. try {
  32. let parseData = token.split('.')[1]
  33. return JSON.parse(atob(parseData))
  34. }
  35. catch (e) {
  36. return undefined
  37. }
  38. }
  39. export function authReducer(state = {}, { type, token }) {
  40. if (type === 'AUTH_LOGIN') {
  41. let payload = jwtDecode(token)
  42. return state = {
  43. token,
  44. payload
  45. }
  46. }
  47. if (type === 'AUTH_LOGOUT') {
  48. // localStorage.removeItem('authToken')
  49. localStorage.clear()
  50. return {}
  51. }
  52. return state
  53. }
  54. // 1 изменение
  55. export const reducers = {
  56. promise: localStoredReducer(promiseReducer, 'promise'),
  57. auth: localStoredReducer(authReducer, 'auth'),
  58. // cart: localStoredReducer(cartReducer, 'cart'),
  59. }
  60. export const totalReducer = combineReducers(reducers)