DeepFrozenStore.mjs 964 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // eslint-disable-next-line import/no-extraneous-dependencies
  2. import deepFreeze from 'deep-freeze'
  3. /* eslint-disable no-underscore-dangle */
  4. /**
  5. * Default store + deepFreeze on setState to make sure nothing is mutated accidentally
  6. */
  7. class DeepFrozenStore {
  8. constructor () {
  9. this.state = {}
  10. this.callbacks = []
  11. }
  12. getState () {
  13. return this.state
  14. }
  15. setState (patch) {
  16. const prevState = { ...this.state }
  17. const nextState = deepFreeze({ ...this.state, ...patch })
  18. this.state = nextState
  19. this._publish(prevState, nextState, patch)
  20. }
  21. subscribe (listener) {
  22. this.callbacks.push(listener)
  23. return () => {
  24. // Remove the listener.
  25. this.callbacks.splice(
  26. this.callbacks.indexOf(listener),
  27. 1,
  28. )
  29. }
  30. }
  31. _publish (...args) {
  32. this.callbacks.forEach((listener) => {
  33. listener(...args)
  34. })
  35. }
  36. }
  37. export default function defaultStore () {
  38. return new DeepFrozenStore()
  39. }