8

I have the following state class:

import { observable, action } from 'mobx';
import axios from 'axios';

export default class AppState {
  @observable user;
  @observable pToken;

  constructor() {
    this.user = {};
    this.pToken = localStorage.getItem('pToken');
  }

  async fetchData(query) {

    const body = JSON.stringify({ query, });
    const response = await axios.post('url', body, {
      headers: {
        'Content-Type': 'application/json',
        token: localStorage.getItem('pToken')
      }
    });

    const user = response.data.data.user;
    console.log('Got user', user);
    this.setUser(user);
  }

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

and in my component:

@inject('store')
@observer
export default class Header extends Component {
    constructor(props) {
        super(props);
        this.store = this.props.store.appState;
    }

    render() {
        const { user } = this.store;
        console.log('store', this.store);

        return (
            <header className='header'>
                User - {user.username}
            </header>
        );
    }
}

Unfortunately, the state user property returns a Proxy object, while the user log shows the user object. Any idea what I'm missing?

enter image description here

Danila
  • 15,606
  • 2
  • 35
  • 67
TheUnreal
  • 23,434
  • 46
  • 157
  • 277

1 Answers1

13

Everything is working as intended, MobX v5 relies on proxies under the hood so when you log observable objects it usually shows some internal implementation.

For more user-friendly output you can use toJS MobX method like that console.log(toJS(user)) or just destructure user object console.log({ ...user })

toJS docs: https://mobx.js.org/refguide/tojson.html

Danila
  • 15,606
  • 2
  • 35
  • 67
  • 1
    I don't want to use `toJS` which I read to be an expensive operation, every time I'm trying to access an object in the store – TheUnreal Sep 27 '20 at 06:13
  • 2
    You don't need to use it to access, just to log things to the console when you develop. To access you use regular dot notation like you already do `user.username` – Danila Sep 27 '20 at 08:11
  • 2
    Oh it confused me! I did `console.log(user)` and saw a proxy, but `user.id` actually works without an expensive operation like toJS! Thanks! – TheUnreal Sep 27 '20 at 08:37
  • For primitive types it works (like strings/numbers) which are not holding the value by references. For objects/array which hold the reference, it returns the proxy. – Naga Kiran May 16 '23 at 13:25