Created
July 1, 2019 12:58
-
-
Save terrysahaidak/b8e0e4f2602a8ebbb4415716012955d3 to your computer and use it in GitHub Desktop.
mobx-react inject/provider with hooks
This file contains 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, { useContext, forwardRef } from 'react'; | |
const MSTContext = React.createContext(null); | |
// eslint-disable-next-line prefer-destructuring | |
export const Provider = MSTContext.Provider; | |
export function useMst(mapStateToProps) { | |
const store = useContext(MSTContext); | |
if (typeof mapStateToProps !== 'undefined') { | |
return mapStateToProps(store); | |
} | |
return store; | |
} | |
export function inject(mapStateToProps) { | |
return function wrapper(Component) { | |
return forwardRef((props, ref) => { | |
const store = useMst(); | |
let propsToPass = store; | |
if (typeof mapStateToProps !== 'undefined') { | |
propsToPass = mapStateToProps(store, props); | |
} | |
return <Component ref={ref} {...propsToPass} />; | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment