React not rerendering after mobx observer change

wiznaibus picture wiznaibus · Oct 1, 2017 · Viewed 11.4k times · Source

Upon page load, I see "hi2" When I click the button, nothing happens. I tried with setUser as well.

I suspect I'm just editing the props themselves and somehow the observable is not being triggered?

See sample code of it not working here in a brand new rails/react environment: https://github.com/bufordtaylor/mobxtest

  1. clone
  2. bundle
  3. rails s
  4. (in another process) ./bin/webpack-dev-server --host 127.0.0.1
  5. navigate to localhost:3000

======================

UPDATE:

I've reduced it to it's basic form, eliminating possible import errors, Provider errors, or constructor errors.

Here it is

import React from 'react'
import ReactDOM from 'react-dom'
import { observable, action, computed } from 'mobx';
import { Provider, inject, observer } from 'mobx-react';


class UserStore {

  @action setUser(val) {
    console.log(val);
    this.user = val;
  }

  @observable user = "default";
}

const userStore = new UserStore();

@observer
class Hello extends React.Component {
  render() {
    return (
      <div>
        hi2 {this.props.userStore.user}
        <button onClick={this.props.userStore.setUser.bind(this,"fwefwe")}>faew</button>
      </div>
    )
  }
}

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Hello userStore={userStore} />,
    document.getElementById('app'),
  )
})

Answer

Alin Ciocan picture Alin Ciocan · May 22, 2018

My problem was the order of wrapping the component, because I was using Material UI framework.

Wrong:

export inject('store')(observer(withStyles(styles)(MyComponent)));

Correct:

export withStyles(styles)(inject('store')(observer(MyComponent)));

So, it's important the order with MobX and React Material UI.