Skip to content

Instantly share code, notes, and snippets.

@amhinson
Created January 18, 2019 19:13
Show Gist options
  • Save amhinson/83f0b0cfced2ed8b23f3a55df40c0a2b to your computer and use it in GitHub Desktop.
Save amhinson/83f0b0cfced2ed8b23f3a55df40c0a2b to your computer and use it in GitHub Desktop.
Unstated HOC
import { ContainerOne, ContainerTwo } from './containers';
// ...
withUnstated(MyComponent, {
one: ContainerOne,
two: ContainerTwo
})
import React, { Component } from 'react';
import { Subscribe, Container } from 'unstated';
import hoistStatics from 'hoist-non-react-statics';
export default (
WrappedComponent: typeof React.Component,
containersObject: object
) => {
class UnstatedComponent extends Component<any> {
render() {
const keys: string[] = Object.keys(containersObject);
const containers: Array<Container<any>> = Object.values(containersObject);
return (
<Subscribe to={[...containers]}>
{(...stores) => {
const storeProps: any = {};
keys.forEach((key, i) => (storeProps[key] = stores[i]));
return <WrappedComponent {...storeProps} {...this.props} />;
}}
</Subscribe>
);
}
}
return hoistStatics(UnstatedComponent, WrappedComponent);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment