Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. const keyMirror = require('keymirror');
  2.  
  3. const ActionSufix = keyMirror({
  4. REQUEST: null,
  5. SUCCESS: null,
  6. ERROR: null,
  7. });
  8.  
  9. const createAction = actionName => {
  10. const action = {};
  11. Object.keys(ActionSufix).forEach(sufix => {
  12. Object.defineProperty(action, sufix, {
  13. get() {
  14. const getter = function (actionPayload = {}) {
  15. return {
  16. type: getter.type,
  17. payload: {
  18. ...actionPayload,
  19. },
  20. };
  21. };
  22. getter.type = `${actionName}_${sufix}`;
  23. getter.payload = {};
  24. return getter;
  25. },
  26. });
  27. });
  28. return action;
  29. };
  30.  
  31. // create action
  32. const loadDataAction = createAction('LOAD_DATA');
  33.  
  34. // action type
  35. console.log(loadDataAction.SUCCESS.type);
  36. // action object
  37. console.log(loadDataAction.SUCCESS);
  38. // action with payload
  39. console.log(loadDataAction.SUCCESS({
  40. id: 123,
  41. }));
  42.  
  43. // Console output:
  44. // LOAD_DATA_SUCCESS
  45. // { [Function: getter] type: 'LOAD_DATA_SUCCESS', payload: {} }
  46. // { type: 'LOAD_DATA_SUCCESS', payload: { id: 123 } }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement