SHARE
TWEET

Untitled

a guest Oct 16th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // object to store the listeners grouped by actionTypes
  2. const listenersMap = {};
  3.  
  4. /**
  5.  * The middleware
  6.  * example usage: createStore(rootReducer, applyMiddleware(thunk, reduxActionListener, reduxLogger))
  7.  */
  8. export const reduxActionListener = store => next => action => {
  9.     // store the prev state to keep it for the listener
  10.     const prevState = store.getState();
  11.     // make sure the original action runs first, so errors won't prevent from running
  12.     const result = next(action);
  13.     // notify all listeners that attached to the type
  14.     const listeners = listenersMap[action.type];
  15.     if (listeners) {
  16.         // eslint-disable-next-line no-console
  17.         console.log(`[ActionListener] Notifying ${listeners.length} listener(s) of action: ${action.type}`);
  18.         const params = { action, state: store.getState(), prevState, store };
  19.         for (const listener of listeners) {
  20.             listener(params);
  21.         }
  22.     }
  23.     // important: return the original result
  24.     return result;
  25. };
  26.  
  27. /**
  28.  * Adds an action listener callback on the specified action type
  29.  * @param {string} actionType
  30.  * @param {listenerFn} function
  31.  * @return the remove function
  32.  */
  33. export const addActionListener = (actionType, listenerFn) => {
  34.     const listeners = listenersMap[actionType] || (listenersMap[actionType] = []);
  35.     listeners.push(listenerFn);
  36.     return () => {
  37.         const index = listeners.indexOf(listenerFn);
  38.         if (index > -1) {
  39.             listeners.splice(index, 1);
  40.         }
  41.     };
  42. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top