6

I am trying to shoe horn mobx into a vr application I am making with react 360. I've tried to use the decorator syntax but after wasting a solid chunk of time trying to implement it, I've decided to use the nondecorator syntax. Here is an example that I came across from the mobx documentation that I have a question on. Here is the code:

import {observer} from "mobx-react";

var timerData = observable({
    secondsPassed: 0
});

setInterval(() => {
    timerData.secondsPassed++;
}, 1000);

@observer class Timer extends React.Component {
    render() {
        return (<span>Seconds passed: { this.props.timerData.secondsPassed } </span> )
    }
};

ReactDOM.render(<Timer timerData={timerData} />, document.body);

Notice the observer declaration on the Timer class. The documentation states this.

Note that using @observer as decorator is optional, observer(class Timer ... { }) achieves exactly the same.

Would this be the correct way of implementing Timer?

observer(class Timer extends React.Component {
  render() {
    return (<span>Seconds passed: { this.props.timerData.secondsPassed } </span> )
  }
}) 
Stefan Becker
  • 5,201
  • 9
  • 17
  • 27
Dan Rubio
  • 3,965
  • 5
  • 34
  • 74

1 Answers1

9

Concerning the code snippet you have added I don't know whether it is a valid way or not, but here's the way I'm using MobX without the decorator syntax in my application project:

Create your MobX store, say MyStore.js like the following:

import {observable, action, computed, decorate} from 'mobx';

export default class MyStore {
    storeMap = observable(new Map());
    storeArray = observable([]);
    storeBoolean = false

    get storeMapSize() {
        return this.storeMap.size;
    }

    setStoreBoolean(value) {
        this.storeBoolean = value;
    }
}

decorate(MyStore, {
    storeMap: observable,
    storeArray: observable,
    storeBoolean: observable

    storeMapSize: computed,

    setStoreBoolean: action
});

Then in your component Timer.js:

import {inject, observer} from "mobx-react";

class Timer extends React.Component {
    render() {
        return (<span>value from store: { this.props.myStore.storeMap.get('any_key') } </span> )
    }
}

export default inject('myStore')(observer(Timer));

and you can create as many stores as you want and inject all of them to your components using the same inject method and use them in the same way via this.props, for example

export default inject('myStore', 'anotherStore', 'anotherNewStore')(observer(Timer));

Mohamed Elsayed
  • 2,173
  • 1
  • 17
  • 34
  • See mobx docs for most up to date usage: https://mobx.js.org/best/decorators.html. @Mis94 looks like you are doing double work in your MyStore example. – cogell Apr 17 '19 at 12:20