Skip to content

Instantly share code, notes, and snippets.

@tho-graf
Last active January 5, 2023 02:15
Show Gist options
  • Save tho-graf/37d11f3a6c72bdac9590bf74b9d59ce8 to your computer and use it in GitHub Desktop.
Save tho-graf/37d11f3a6c72bdac9590bf74b9d59ce8 to your computer and use it in GitHub Desktop.
import * as React from "react";
type Value = boolean;
type ContextWithSetter = React.Context<{
value: Value;
setValue: (value: Value) => void;
}>;
const { Provider, Consumer }: ContextWithSetter = React.createContext({
value: false,
// tslint:disable-next-line:no-empty
setValue: (value: Value) => {}
});
interface State {
value: Value;
setValue: (value: Value) => void;
}
interface Props {
defaultValue: Value;
}
class ProviderWithSetter extends React.Component<Props, State> {
public constructor(props: Props) {
super(props);
this.state = {
value: props.defaultValue,
setValue: this.setValue
};
}
public render() {
return <Provider value={this.state}>{this.props.children}</Provider>;
}
private setValue = (value: Value) => this.setState({ value });
}
export { ProviderWithSetter as Provider, Consumer };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment