Home > OS >  Observer not working with useLocalObservable
Observer not working with useLocalObservable

Time:03-24

import { Observer, useLocalObservable } from 'mobx-react-lite';

function App() {
  const { count, decrement, increment } = useLocalObservable(() => ({
    count: 0,
    increment() { this.count   },
    decrement() { this.count-- },
  }));

  return (
    <div>
      <Observer>{() => (<div>{count}</div>)}</Observer>
      <button onClick={() => { decrement() }} >decrement</button>
      <button onClick={() => { increment() }} >increment</button>
    </div>
  );
}

Observer not working with useLocalObservable.when I click on the buttons nothing is updated. What is the reason ?

CodePudding user response:

The Observer tracks all the observable data that is dereferenced inside of it and re-renders when that observable data changes. When you dereference count from your observable outside of the Observer it is just a regular JavaScript number from that point onwards, so there is nothing for Observer to track.

You could instead dereference it inside the Observer and it will work:

import { Observer, useLocalObservable } from 'mobx-react-lite';

function App() {
  const state = useLocalObservable(() => ({
    count: 0,
    increment() { state.count   },
    decrement() { state.count-- },
  }));

  return (
    <div>
      <Observer>{() => <div>{state.count}</div>}</Observer>
      <button onClick={state.decrement}>decrement</button>
      <button onClick={state.increment}>increment</button>
    </div>
  );
}
  • Related