MobX Store Provider Component Decorator
npm install mobx-provideMobX Store Provider Component Decorator








Do you like the convenience of importing store directly to your MobX component, but find testing a bit tricky? With mobx-provide decorator, you can still retain your imports, pass the store as props through the decorator, and just prepend your store with props or this.props or use destructuring like const {store} = this.props before the return statement in your render() method.
The mobx-provide is a decorator or higher-order component, that accepts a store object and a component as inputs, and returns a (enhanced) component.
``js`
const store = {usersStore, articlesStore, adminStore}
const ObserverComponentWithStore = provide(store)(observer(Component))
or
`js`
const ObserverComponentWithStore = provide({
usersStore,
articlesStore,
adminStore
})(observer(Component))
`js
import React from 'react'
import { observer } from 'mobx-react'
import userProfile from 'stores/userProfile'
export class UserProfile extends React.Component {
render () {
return (
Name: {userProfile.name}
Email: {userProfile.email}
export default observer(UserProfile)
`
`js
import React from 'react'
import { observer } from 'mobx-react'
import userProfile from 'stores/userProfile'
import provide from 'mobx-provide'
export class UserProfile extends React.Component {
render () {
const {userProfile} = this.props
return (
Name: {userProfile.name}
Email: {userProfile.email}
const ObserverComponent = observer(UserProfile)
export default provide({userProfile})(ObserverComponent)
`
`diff`
+ const {userProfile} = this.props
return (
...
)
`diff`
- export default observer(UserProfile)
+ const ObserverComponent = observer(UserProfile)
+ export default provide({userProfile})(ObserverComponent)
There is not much difference between the two. You just have to reference the store using props:
const {userProfile} = this.props
Basically, you have to have two exports for your component, named export and default export. Your named export could be the plain component for your testing, and the default export for enhanced or observer component.
In your test file, import the plain component, create a new instance of your store and pass it as props as you normally would. Simple!
To contribute, please follow these steps:
1. Fork the repo
1. Make a branch for your change
1. Run npm installgit add -A
1. Make your changes
1. Run to add your changesnpm run commit
1. Run (Do not use git commit)git push`
1. Push your changes with
1. Create the Pull Request
1. All done and celebrate!
>Be the first to contribute!
MIT © Felipe Apostol