Skip to content

Instantly share code, notes, and snippets.

@Jiert
Last active May 8, 2017 16:46
Show Gist options
  • Save Jiert/7986705590738e3410834230d7b490aa to your computer and use it in GitHub Desktop.
Save Jiert/7986705590738e3410834230d7b490aa to your computer and use it in GitHub Desktop.
How to use hashed with Redux
// URL hash should be the keeper of its own state. In this example we're using the "comparing" state,
// i.e. are we in compare mode or not. Since the toggle button lives in the sidebar, we would do something
// like this in the sidebar component:
getInitialState() {
comparing: false
}
componentWillMount() {
this.updateHash = hashed.register({comparing: false}, this.onHashChange);
}
// If the hash is manually modified, we set state based on that modification:
onHashChange(hash) {
this.setState({comparing: hash.comparing});
}
// When a user takes action, we update the hash, and update the state
onClickHandler() {
const comparing = !this.state.comparing
this.updateHash({comparing});
this.setState({comparing});
}
// Comparing state can then be passed down to other components as props
// Pros: decouples hash and store state, prevent duplication and syncing trickiness.
// Cons: requires us to wire up components that need shared hash state.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment