This one is piece of cake in React. If you want your MobX store to be available in any React component, you just use mobx-react @inject
component. Something like:
import React from 'react';
import {inject} from 'mobx-react';
@inject('myStore')
class Dummy extends React.Component {
Then, my store is available as a prop:
this.props.myStore.myMethod();
Nice, convenient... and React only. Maybe I'm missing something, but I can't find a way to access my store from a plain ES6 class. How do I get the same result in a plain ES6 class in pure Vanilla Javascript?
Answer found in MobX GitHub account by adonis-work. Quoting the answer:
Exporting store as a singleton:
// Store.js
import { observable, computed } from 'mobx'
class Store {
@observable numClicks = 0
@computed get oddOrEven() {
return this.numClicks % 2 === 0 ? 'even' : 'odd'
}
}
const store = new Store()
export default store
... enables us to import and use the active store anywhere in the app as many times we want.
// Component.jsx
import store from Store
// use the global store in any component without passing it
// down through the chain of props from the root node
store.numClicks = 4
console.log(store.oddOrEven)
I am using this approach without problems for some time now. Are there any caveats I should look out for?
Link to source: https://github.com/mobxjs/mobx/issues/605
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