I cant figure out mobx-react...
How do I pass props from a mobx observable to a mobx-react observer?
The code below doesn't works, but I feel like it should. Can someone tell me what is going wrong?
let mobxData = observable({information: "this is information"});
@observer class Information extends React.Component {
render() {
console.log(this.props.mobxData.information);
return (
<h1>class: {this.props.mobxData.information}</h1>
)
}
};
const StatelessInformation = observer(({mobxData}) => {
console.log(mobxData.information);
return <h1>stateless: {mobxData.information}</h1>
});
ReactDOM.render(
<div>
<Information/>
<StatelessInformation/>
</div>,
document.getElementById('app')
);
I've not done much mobx lately and not tested this but typically you'd have a provider somewhere and then use the @inject
to pass stores as props
Consumer of information:
import { observer, inject } from 'mobx-react'
@inject('information')
@observer
class Information extends React.Component {
render(){
{this.props.information.foo}
}
}
model level - very basic
import { observable, action } from 'mobx'
class Information {
@observable foo = 'bar'
@action reset(){
this.foo = 'foo'
}
}
export new Information()
Root provider level
import { Provider } from 'mobx-react'
import Information from ./information'
<Provider information={Information}>
<Information />
</Provider>
// test it...
setTimeout(() => {
Information.foo = 'back to foo'
}, 2000)
but ultimately you can probably work with whatever you pass in the Provider
Under the hood, the provider is probably just passing context
via childContextType
and contextType
when a HOC memoises it and maps to props
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With