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.2KB

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