Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React not rerendering after mobx observer change

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'),
  )
})
like image 451
wiznaibus Avatar asked Oct 01 '17 13:10

wiznaibus


2 Answers

if you use the latest version of mobx, and babel version 7.12 add this to you constructor

makeObservable(this)
like image 72
tarik203 Avatar answered Oct 16 '22 04:10

tarik203


For anyone arriving here, make sure you're not being a complete idiot like me and that you didn't forget to add the @observer decorator before the class component.

(Or the @observable decorator in the store)

God, wasted a full day on that

like image 40
jonyB Avatar answered Oct 16 '22 05:10

jonyB