0

The latest MobX 6.0.1 release has a syntax that appears in the example app at https://codesandbox.io/s/minimal-observer-p9ti4 that I don't understand.

The code is:

const TimerView = observer(({ timer }: { timer: Timer }) => (
  <span>Seconds passed: {timer.secondsPassed}</span>
));

The syntax function({arg1,arg2}) I've seen and understand, but not function({arg1: {arg1: arg2}}) and since the MobX docs don't help; I'm asking here.

What I've tried

So I looked up the docs for MobX observer and found https://mobx.js.org/api.html#observer-1 which doesn't help. It says:

observer

Usage: observer(component)

A higher order component you can use to make a functional or class based React component re-render when observables change.

I'm looking over the website more but hopefully this question and forthcoming answer will help someone else out.

PatS
  • 8,833
  • 12
  • 57
  • 100
  • 2
    The code in your link is TypeScript, not JavaScript -- it has extension `.tsx` – Barmar Oct 20 '20 at 01:31
  • 1
    i using mobx in current native project and i know documentation sucks..... but they help me : [Maksim Ivanov](https://www.youtube.com/watch?v=MKNls_FReXI) [Ben Awad](https://www.youtube.com/watch?v=oQiMXRsO4o4&t=218s) – Robert Oct 20 '20 at 01:34
  • Oh, well that explains it! Then the 2nd `{timer: Timer}` is the structure of the variable. Thanks. I missed that. – PatS Oct 20 '20 at 01:38
  • As mentioned. It is Typescript. Are you familiar with C or Java? In C/Java types are defined as `number x` but Typescript uses `x: number`. Therefore the observer has a type `x: Object` and not any kind of object but an object that looks like `{timer: somevalue}` where again the type of `timer` is the `Timer` class as defined by `timer: Timer`. The rest is regular argument destructuring. In javascript the syntax is simply `observer(({timer}) => { ...` – slebetman Oct 20 '20 at 01:38
  • ... everything after the `:` is Typescript stuff and not part of javascript syntax – slebetman Oct 20 '20 at 01:39

1 Answers1

1

It's saying that your observer callback has an object argument with a timer property. That timer property is of type Timer.

The object is then destructured to extract the timer property to the variable timer.

Think of it like this

interface Timer {
  secondsPassed: number
}
interface Component {
  timer: Timer
}
const TimerView = observer((obj: Component) => (
  <span>Seconds passed: {obj.timer.secondsPassed}</span>
));
Phil
  • 157,677
  • 23
  • 242
  • 245