Created
January 18, 2019 19:13
-
-
Save amhinson/83f0b0cfced2ed8b23f3a55df40c0a2b to your computer and use it in GitHub Desktop.
Unstated HOC
This file contains hidden or 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
import { ContainerOne, ContainerTwo } from './containers'; | |
// ... | |
withUnstated(MyComponent, { | |
one: ContainerOne, | |
two: ContainerTwo | |
}) |
This file contains hidden or 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
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