Reputation: 7219
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
Upvotes: 0
Views: 574
Reputation: 15464
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
Upvotes: 2
Reputation: 19059
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 :).
Upvotes: 2