Advertisement
AllenYuan

auth - middleware update

Apr 24th, 2020
506
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const promiseMiddleware = store => next => action => {
  2.   // if the action's payload is a promise, trigger this middleware
  3.   if (isPromise(action.payload)) {
  4.     // trigger UI's loading state
  5.     store.dispatch({ type: 'ASYNC_START', subtype: action.type });
  6.     // let promise succeed/fail
  7.     action.payload.then(
  8.       // if it succeeds, mutate payload into the promised data and
  9.       // dispatch action to store
  10.       res => {
  11.         action.payload = res;
  12.         store.dispatch(action);
  13.       },
  14.       // failure => set an error flag on action and mutate payload into
  15.       // the error message. dispatch action to store
  16.       error => {
  17.         action.error = true;
  18.         action.payload = error.response.body;
  19.         store.dispatch(action);
  20.       }
  21.     );
  22.  
  23.     return;
  24.   }
  25.  
  26.   // if the action payload is not a promise, send the action over to the next middleware
  27.   // or dispatch it to the store if this is the last middleware in the chain
  28.   next(action);
  29. }
  30.  
  31. function isPromise(v) {
  32.   return v && typeof v.then === 'function';
  33. }
  34.  
  35. export {
  36.   promiseMiddleware
  37. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement