Skip to content

Instantly share code, notes, and snippets.

@terrysahaidak
Created July 1, 2019 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terrysahaidak/b8e0e4f2602a8ebbb4415716012955d3 to your computer and use it in GitHub Desktop.
Save terrysahaidak/b8e0e4f2602a8ebbb4415716012955d3 to your computer and use it in GitHub Desktop.
mobx-react inject/provider with hooks
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