0

globalStore.js

import {observable} from 'mobx';

export default class globalStore {
    @observable loggedIn = false;
}

Followed by main App.js:

import LoginForm from './src/components/LoginForm';
import { observer } from 'mobx-react';
import globalStore from './src/store/globalStore';

which renders loginForm:

      return (
            <LoginForm store={globalStore} />
      );

In LoginForm, I wish to access the "loggedIn" observable:

observer

class LoginForm extends Component { / ... 

render() {
        console.log(this.props.store.loggedIn); 

Result: undefined

Desired result: false

Why does this not work?

Do I need a Provider wrapping the LoginForm component? How come?

Wrapping my entire in the App.js in a Provider with the store does not work either

cbll
  • 4,389
  • 13
  • 54
  • 95

2 Answers2

2

I cannot see the instance of your global store class

try

import {observable} from 'mobx';

class globalStore {
    @observable loggedIn = false;
}
const global_store=new globalStore(); // as a singleton class
export default global_store;

then your login form will be like below

 return (
            <LoginForm store={global_store} />
      );

or may be you can instantiate it on your login form as well

sumit
  • 13,148
  • 10
  • 57
  • 103
2

I think there are few things from my point of view I've doing differently with a working implementation:

First you need to create new store from your GlobalStore. I've done it this way:

class GlobalStore {
  @observable loggedin = false;
  ...
}

const store = new GlobalStore();
export default store;

Then you should use provider:

import GlobalStore from './path/to/stores/GlobalStore';

<Provider
  globalStore={GlobalStore}
>
  <AppRelatedContainers />
</Provider>

Finally you should inject your store in login form:

@inject('globalStore')
class LoginForm extends Component {
...

  render() {
    console.log(this.props.globalStore.loggedIn);
    ...
  }

With these steps you should end up with a working solution. I know MobX can be pain in the ass when you work with it initially. But then it eases up and you're good to go :).

Samuli Hakoniemi
  • 16,628
  • 1
  • 55
  • 71
  • I actually learned MobX a year ago... Apparently I have forgot. And yes, pain in the ass at first, but i'm getting the gist of it again. THanks for your solution :) – cbll Dec 12 '17 at 21:27