Skip to content

Instantly share code, notes, and snippets.

@shazmodan
Last active September 8, 2017 12:57
Show Gist options
  • Save shazmodan/c83c508a3480d9a7627be929ce1f2317 to your computer and use it in GitHub Desktop.
Save shazmodan/c83c508a3480d9a7627be929ce1f2317 to your computer and use it in GitHub Desktop.
JavaScript Redux Observe Store Subscribe
export const observeStore = (store, select, onChange) => {
  let currentState

  function handleChange() {
    const nextState = select(store.getState())

    if (nextState !== currentState) {
      currentState = nextState
      onChange(currentState)
    }
  }

  const unsubscribe = store.subscribe(handleChange)

  handleChange()

  return unsubscribe
}

const store = configureStore({
  specificState: {
    enabled: true
  }
})

// Store setup
this.store: {
  subscribe: (select, onChange) => observeStore(store, select, onChange),
  getState: store.getState,
  dispatch: store.dispatch
}

// Use it like this
this.store.subscribe(fullState => fullState.specificState, mySpecificState => {
  this.buttonEnabled = mySpecificState.enabled
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment