Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access MobX state outside of React Components?

I'm using a MobX store to hold some user authentication data as an observable. I'd like to access some data for some functions I'd like to run outside of the inject/observer pattern with components. Is that wise to do?

For example an authenication function as so:

function authMe() { ...access mobx data here to perform conditional logic}
like image 336
eddiewang Avatar asked Oct 29 '22 07:10

eddiewang


1 Answers

I agree with user1628461, but if your application grows, it can be problematic to repeatedly pass the store as an argument.

A possibility you have is to first initialise your store, to then pass it as parameter when initialising your helper class. This way you can save a reference to the store, its observables, and access it when needed. See example:

App.jsx

import Store from './store.jsx'
import Helper from './helper.jsx'

const myStore = new Store();
const myHelper = new Helper(myStore);

myHelper.doSomething();

helper.jsx

export default class Helper {

  constructor(store){
    this.store = store;
  }

  doSomething() {
    // do something with the store
    this.store.useAction();
    this.store.anObservable = 'modified';
  }
}
like image 129
Flavien Knuchel Avatar answered Nov 11 '22 08:11

Flavien Knuchel