Created
May 27, 2018 12:49
-
-
Save threepointone/d12a0a4cce8bc82e1dddd57ee9b74702 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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