Skip to content Skip to sidebar Skip to footer

React Native And MobX: How To Create A Global Store?

I am currently trying to implement a mobx storage which I can call from everywhere like so: import {userStore} from '../UserStore.js'; At the end of the file, my export functional

Solution 1:

You simply need a singleton instance of UserStore class

Sample demo

let localInstance = null;

export class Apple {
  static newInstance() {
    if (! localInstance)
      localInstance = new Apple();
    return localInstance;
  }
}

// usage

import {Apple} from './apple';
const instance = Apple. newInstance();

In your case, you can use a simple function

import {observable, computed, action} from 'mobx';
import {ObservableMap, toJS} from 'mobx';
import {Fb} from './firebase.js';

class UserStore {
  // omitted
}

let userStore;
export function getUserstore() {
  if (!userStore)
    userStore = new UserStore();
  return userStore;
};

Somewhere in code

// instead of 
import {userStore} from './someUserStoreModule';

// use 
import {getUserstore} from './someUserStoreModule';
const userStore = getUserstore();

Post a Comment for "React Native And MobX: How To Create A Global Store?"