Get State from mobx store react js

Viewed 764

I am just learning React JS. I want to get a value that is stored in mobx state in my application. But not getting any idea how to get mobx state in functional component.

const user_id = observer(({ GlobalStore }) =>
    console.log(GlobalStore.user_id)
); // I just need the user ID.

This is the full code:

import { observer } from "mobx-react";
import Store from "../mobx/Store";

export const user_id = observer(({ GlobalStore }) =>
    console.log(GlobalStore)
);

console.log(user_id);

And my Store.js file is as below:

import { observable, action, makeObservable, autorun } from "mobx";
class GlobalStore {
    site_title = "ABCD";
    app_code = null;
    user_id = null;

    constructor() {
        makeObservable(this, {
            site_title: observable,
            app_code: observable,
            user_id: observable,
            update_title: action.bound,
            update_appcode: action.bound,
            update_userid: action.bound,
        });
    }

    update_title(title) {
        this.site_title = title;
    }
    update_appcode(code) {
        this.app_code = code;
    }
    update_userid(id) {
        this.user_id = id;
    }
}

const Store = new GlobalStore();
autorun(() => {
    console.log("System Checking... OK")
})
export default Store;

1 Answers

Because your store is a singleton you can just import it anywhere and access any field or method.

import { observer } from 'mobx-react';

import Store from './Store';

const SomeComponent = observer(() => {
  return <div>user_id: {Store.user_id}</div>;
});

I've made example on Codesandbox

Related