reducers.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import {createStore, applyMiddleware, combineReducers} from 'redux';
  2. import thunk from 'redux-thunk';
  3. //----------------------------PromiseReducer---------------------------
  4. export 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 actionPending = (name) => ({type: 'PROMISE', status: 'PENDING', name})
  14. const actionFulfilled = (name, payload) => ({type: 'PROMISE', status: 'FULFILLED', name, payload})
  15. const actionRejected = (name, error) => ({type: 'PROMISE', status: 'REJECTED', name, error})
  16. export const actionPromise = (name, promise) =>
  17. async dispatch => {
  18. dispatch(actionPending(name)) //сигнализируем redux, что промис начался
  19. try{
  20. const payload = await promise //ожидаем промиса
  21. dispatch(actionFulfilled(name, payload)) //сигнализируем redux, что промис успешно выполнен
  22. return payload //в месте запуска store.dispatch с этим thunk можно так же получить результат промиса
  23. }
  24. catch (error){
  25. dispatch(actionRejected(name, error)) //в случае ошибки - сигнализируем redux, что промис несложился
  26. }
  27. }
  28. //--------------------------------jwtDecode---------------------------------
  29. function jwtDecode(token){
  30. try{
  31. let payload = JSON.parse(atob(token.split('.')[1]));
  32. return payload;
  33. } catch(e){
  34. }
  35. }
  36. //--------------------------------authReducer-------------------------------------
  37. export function authReducer(state,{type, token}){
  38. if(state === undefined){
  39. if(localStorage.authToken){
  40. type = 'AUTH_LOGIN';
  41. token = localStorage.authToken
  42. }
  43. }
  44. if(type === 'AUTH_LOGIN'){
  45. let payload = jwtDecode(token);
  46. if(payload){
  47. localStorage.authToken = token;
  48. return {token,payload}
  49. }
  50. }
  51. if(type === 'AUTH_LOGOUT'){
  52. localStorage.authToken = '';
  53. return {};
  54. }
  55. return state || {};
  56. }
  57. const actionAuthLogin = token => ({type: 'AUTH_LOGIN', token})
  58. const actionAuthLogout = () => ({type: 'AUTH_LOGOUT'})
  59. const store = createStore(promiseReducer, applyMiddleware(thunk))
  60. store.subscribe(() => console.log(store.getState()))
  61. export default store;