Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Mobx - component not updating after store change

Using Mobx, after updating the store (i.e. clicking the button) the component does not re-render. I've installed mobx devtools which shows nothing after the initial load, and there is no error in the console. Any ideas what I've done wrong?

Store.js:

import { observable } from 'mobx';

class Store {

    @observable me;

    constructor() {
        this.me = 'hello';
    }

    change_me(){
        this.me = 'test 1234';

    }

}


export default Store;

layout.js:

import React from "react";
import { observer } from 'mobx-react';


@observer
export default class Layout extends React.Component{

    render(){

        return(
            <div>
                <h1>{this.props.store.me}</h1>
              <button onClick={this.on_change}>Change</button>
            </div>
        )
    }

    on_change = () => {
        this.props.store.change_me();
    }
}

index.js:

import React from "react";
import ReactDOM from "react-dom";
import Layout from "./components/Layout";
import Store from "./Store";
import DevTools, { configureDevtool } from 'mobx-react-devtools';

// Any configurations are optional
configureDevtool({
    // Turn on logging changes button programmatically:
    logEnabled: true,
    // Turn off displaying conponents' updates button programmatically:
    updatesEnabled: false,
    // Log only changes of type `reaction`
    // (only affects top-level messages in console, not inside groups)
    logFilter: change => change.type === 'reaction',
});


const app = document.getElementById('app');
const store = new Store();

ReactDOM.render(

    <div>
        <Layout store={store} />
        <DevTools />
    </div>
, app);
like image 603
Chris Avatar asked Nov 20 '16 09:11

Chris


2 Answers

Just add makeObservable(this); in constructor function like below

    constructor() {
       makeObservable(this);
    }
like image 125
BHANU PRATAP SINGH THAKUR Avatar answered Nov 12 '22 18:11

BHANU PRATAP SINGH THAKUR


I would start by adding @action to your change_me() function. From what I understand, it's not always completely required, but I have encountered problems like this in my own code several times when I've forgotten to add it.

Additionally post your .babelrc as @mweststrate suggested, as it will help others to check that the proper plugins are loaded.

like image 31
cdoc Avatar answered Nov 12 '22 19:11

cdoc