what does "@observer" attribute do?

693 Views Asked by At

First thing I learnt about mobx-react is use "@observer" attribute to track values of properties which defined in state class.. this is my sample below;

//@observer cut it off
SingUp.js

    import React, {Component} from 'react'
    import {observer} from 'mobx-react'

class SignUp extends Component{
  constructor(props){
    super(props)
  }
  SaveUser(e){
    e.preventDefault();
    this.props.appState.user.username = this.username.value;
    this.props.appState.user.password = this.password.value;
    this.props.appState.postSaveUser();
  }
  render(){<form onSubmit={()=>this.SaveUser(e)}>...

when I submit the form it "SaveUser()" called and set app state values. you see I dont define "@observer" attribute at top of SignUp class

and here is state class; AppState.js

import { observable, action} from "mobx"
import {user} from './models/user'

class AppState {
  @observable user=new user;
  constructor() {
  }
  postSaveUser(){
      debugger
      var asd = this.user
  }
}

the thing is when I check the values in "postSaveUser()" method I see values exactly I set it "SignIn" component, is it weird?

I thought it only track values assigned in any class which defined with "@observer" attribute but although I dont use it I am able to access data?

1

There are 1 best solutions below

0
On BEST ANSWER

Using the @observer decorator on a React component class is much like using autorun. The component will re-render when the observables that got de-referenced in the last render are changed. You can still of course change the value of observable data, it is just that your React component will not re-render automatically if you don't use the @observer decorator.

Example (JSBin)

class Store {
  @observable data = 'cool';
}

const store = new Store();

setTimeout(() => {
  store.data = 'wow';
}, 2000);


@observer 
class Observer extends Component {
  render() {
    return <h1> This component will re-render when {store.data} changes.</h1>; 
  }
};

class NonObserver extends Component {
  render() {
    return <h1> This component will NOT re-render when {store.data} changes.</h1>; 
  }
};

ReactDOM.render(
  <div>
    <Observer />
    <NonObserver />
  </div>,
  document.getElementById('app')
);