You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // @flow
  2. import _ from 'lodash';
  3. import MiddlewareRegistry from './MiddlewareRegistry';
  4. import PersistenceRegistry from './PersistenceRegistry';
  5. import { toState } from './functions';
  6. /**
  7. * The delay in milliseconds that passes between the last state change and the
  8. * persisting of that state in the storage.
  9. */
  10. const PERSIST_STATE_DELAY = 2000;
  11. /**
  12. * A throttled function to avoid repetitive state persisting.
  13. */
  14. const throttledPersistState
  15. = _.throttle(
  16. state => PersistenceRegistry.persistState(state),
  17. PERSIST_STATE_DELAY);
  18. // Web only code.
  19. // We need the <tt>if</tt> because it appears that on mobile the polyfill is not
  20. // executed yet.
  21. if (typeof window.addEventListener === 'function') {
  22. window.addEventListener('unload', () => {
  23. throttledPersistState.flush();
  24. });
  25. }
  26. /**
  27. * A master MiddleWare to selectively persist state. Please use the
  28. * {@link persisterconfig.json} to set which subtrees of the redux state should
  29. * be persisted.
  30. *
  31. * @param {Store} store - The redux store.
  32. * @returns {Function}
  33. */
  34. MiddlewareRegistry.register(store => next => action => {
  35. const oldState = toState(store);
  36. const result = next(action);
  37. const newState = toState(store);
  38. oldState === newState || throttledPersistState(newState);
  39. return result;
  40. });