Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass props from mobx-observable to mobx-react observable?

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')
);
like image 347
joeydebreuk Avatar asked Oct 30 '22 03:10

joeydebreuk


1 Answers

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.

like image 166
Dimitar Christoff Avatar answered Nov 09 '22 22:11

Dimitar Christoff