Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created May 27, 2018 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save threepointone/d12a0a4cce8bc82e1dddd57ee9b74702 to your computer and use it in GitHub Desktop.
Save threepointone/d12a0a4cce8bc82e1dddd57ee9b74702 to your computer and use it in GitHub Desktop.
// this component freezes redux state for its children when `cold` is true
// after every render, it saves a snapshot of the last used redux state
// it also replacies the redux store with a 'proxy' store, which, when cold
// - no-ops all action dispatches
// - returns state from the snapshot
class Freeze extends Component<{ cold: boolean, children: Node }> {
context: {
store: Store,
};
static contextTypes = {
store: x => null,
};
// our proxy store
store = {
getState: () => {
if (this.props.cold) {
return this.snapshot;
}
return this.context.store.getState();
},
dispatch: action => {
if (!this.props.cold) {
this.context.store.dispatch(action);
}
},
subscribe: listener => {
return (
this.context.store.subscribe(() => {
if (!this.props.cold) {
listener();
}
})
);
},
replaceReducer: next => {
// should this be a no-op too?
return this.context.store.replaceReducer(next);
},
};
snapshot = this.context.store && this.context.store.getState();
componentDidUpdate() {
if (this.context.store && !this.props.cold) {
this.snapshot = this.context.store.getState();
}
}
render() {
return <Provider store={this.store}>{this.props.children}</Provider>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment