Skip to content

Instantly share code, notes, and snippets.

@slorber
Created June 27, 2018 16:50
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 slorber/c9deabe31bb831e7dc17204a1db35f6b to your computer and use it in GitHub Desktop.
Save slorber/c9deabe31bb831e7dc17204a1db35f6b to your computer and use it in GitHub Desktop.
import React from 'react';
// Permit to create a provider/consumer but allow the consumer
// to also receive a setter to update the provider value
export const createUpdatableContext = () => {
const { Provider, Consumer } = React.createContext(null);
class UpdatableContextProvider extends React.Component {
constructor(props) {
super(props);
this.state = {
realValue: props.value,
setter: value => {
this.setState({ realValue: value });
},
};
}
render() {
return <Provider value={this.state}>{this.props.children}</Provider>;
}
}
class UpdatableContextConsumer extends React.Component {
render() {
return (
<Consumer>
{value => this.props.children(value.realValue, value.setter)}
</Consumer>
);
}
}
return {
Provider: UpdatableContextProvider,
Consumer: UpdatableContextConsumer,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment