Browse Source

Use hooks for context

master
Alex Mikhalev 6 years ago
parent
commit
39323369bb
  1. 12
      client/state/reactContext.tsx

12
client/state/reactContext.tsx

@ -33,20 +33,16 @@ export function ConsumeState({ children }: ConsumeStateProps) {
export function injectState<P extends { appState: AppState }>( export function injectState<P extends { appState: AppState }>(
Component: React.ComponentType<P> Component: React.ComponentType<P>
): React.ComponentClass<Omit<P, "appState">> { ): React.FunctionComponent<Omit<P, "appState">> {
return class extends React.Component<Omit<P, "appState">> { return function InjectState(props) {
render() { const state = React.useContext(StateContext);
const consumeState = (state: AppState | null) => {
if (state == null) { if (state == null) {
throw new Error( throw new Error(
"Component with injectState must be mounted inside ProvideState" "Component with injectState must be mounted inside ProvideState"
); );
} }
// tslint:disable-next-line: no-object-literal-type-assertion // tslint:disable-next-line: no-object-literal-type-assertion
const allProps: Readonly<P> = {...this.props, appState: state} as Readonly<P>; const allProps: Readonly<P> = {...props, appState: state} as Readonly<P>;
return <Component {...allProps} />; return <Component {...allProps} />;
};
return <StateContext.Consumer>{consumeState}</StateContext.Consumer>;
} }
};
} }

Loading…
Cancel
Save