123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- // promiseReducer
- import { combineReducers } from "redux"
- export function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
- if (type === 'PROMISE') {
- return {
- ...state,
- [nameOfPromise]: { status, payload, error }
- }
- }
- return state
- }
- // localStoredReducer
- export function localStoredReducer(originalReducer, localStorageKey) {
- function wrapper(state, action) {
- if (!state) {
- try {
- return JSON.parse(localStorage[localStorageKey])
- }
- catch (error) {
- }
- }
- const newState = originalReducer(state, action)
- localStorage[localStorageKey] = JSON.stringify(newState)
- return newState
- }
- return wrapper
- }
- // authReducer
- // раскодируем JWT-токен
- const jwtDecode = function (token) {
- try {
- let parseData = token.split('.')[1]
- return JSON.parse(atob(parseData))
- }
- catch (e) {
- return undefined
- }
- }
- export function authReducer(state = {}, { type, token }) {
- if (type === 'AUTH_LOGIN') {
- let payload = jwtDecode(token)
- return state = {
- token,
- payload
- }
- }
- if (type === 'AUTH_LOGOUT') {
- // localStorage.removeItem('authToken')
- localStorage.clear()
- return {}
- }
- return state
- }
- // 1 изменение
- export const reducers = {
- promise: localStoredReducer(promiseReducer, 'promise'),
- auth: localStoredReducer(authReducer, 'auth'),
- // cart: localStoredReducer(cartReducer, 'cart'),
- }
- export const totalReducer = combineReducers(reducers)
|