Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing MobX store in vanilla ES6 Javascript class

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?

like image 743
Ignacio Segura Avatar asked Apr 16 '18 10:04

Ignacio Segura


1 Answers

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

like image 147
Ignacio Segura Avatar answered Sep 24 '22 15:09

Ignacio Segura