1

I am using mobx & mobx-react-lite for first time and I can see the @action is not firing any events.

Please find the Code SandBox url here

My intention is when I click on button, the name CHAN should change to XIAN. But it's not happening. Can you please let me know where I made wrong? Thanks in advance.

METALHEAD
  • 2,734
  • 3
  • 22
  • 37

2 Answers2

1

You are missing the makeObservable in the myStore constructor.

Codesandbox

Documentation

import { observable, action, makeObservable } from "mobx";

export class myStore {
  @observable name: string = "CHAN";

  constructor() {
    makeObservable(this)
  }

  @action
  setName(newName: string) {
    this.name = newName;
  }
}
Chris
  • 6,331
  • 1
  • 21
  • 25
  • 1
    It didn't allow me to accept the answer for first few minutes. I have accepted it now. Thank you so much for your time. – METALHEAD Oct 14 '20 at 17:25
  • I just have one more basic question. Is wrapping the `observer` once around the code in `app.tsx` is enough for the entire app to make it reactive? – METALHEAD Oct 14 '20 at 19:17
  • 1
    No, you should wrap each component which should be reactive with `observer`. This is because `observer` only subscribes to consumed properties in its own render function. E.g. if you pass the complete store to a child component, it won't re-rerender because the store itself won't change. – Chris Oct 15 '20 at 09:15
1

In addition to @Christiaan answer, you can also use makeAutoObservable and drop decorators altogether!

import { observable, action, makeAutoObservable } from "mobx";

export class myStore {
  name: string = "CHAN";

  constructor() {
    makeAutoObservable(this)
  }

  setName(newName: string) {
    this.name = newName;
  }
}

More info: https://mobx.js.org/react-integration.html

Danila
  • 15,606
  • 2
  • 35
  • 67
  • I will make a note of it. Thank you so much. – METALHEAD Oct 14 '20 at 19:23
  • I just have one more basic question. Is wrapping the observer once around the code in app.tsx is enough for the entire app to make it reactive? – METALHEAD Oct 14 '20 at 19:23
  • 1
    Nope, you need to wrap every component which uses any observable or computed value. It's easier to jut wrap everything, honestly. – Danila Oct 15 '20 at 08:12