Mobx Cheat Sheet

From WikiOD

Here is the cheatsheat of Mobx and basic guide on how to use Mobx

Properties[edit | edit source]

import {observable, computed} from 'mobx'

class Page {
  @observable title = ''
  @observable published = false
  @observable author = null

  @computed get authorName () {
    return this.author || 'Anonymous'
  }
}

Actions[edit | edit source]

class Page {
  @action publish () {
    this.published = true
    // do ajax/async here if you like
  }
}

Plain objects[edit | edit source]

const person = observable({
  name: 'Ella Fitzgerald'
})
const temp = observable(23)
temp.get()
temp.set(25)
temp.observe(...)

Reactions[edit | edit source]

Importing[edit | edit source]

import {autorun, autorunAsync, when} from 'mobx'

autorun()[edit | edit source]

// Runs it, finds out what it accessed, then observe those
autorun(() => {
  console.log(page.title)
})

when()[edit | edit source]

class Foo {
  constructor () {
    when(
      () => !this.isVisible,
      () => this.doSomething())
  }
}

expr()[edit | edit source]

// A temporary computed value. Its result is cached.
render () {
  const isPublished = expr(() => page.published === true)
  if (isPublished) { ... }
}

Modifiers[edit | edit source]

  • asMap(obj) - JS map (dynamic keys)
  • asReference(fn) - don’t observe me
  • asStructure(obj) - JS object (observe as deepEqual)
  • asFlat(array) - JS array (observe its children)

React[edit | edit source]

mobx-react[edit | edit source]

import { observer } from 'mobx-react'

@observer
class PageView extends React.Component {
  render () {
    return <div>{this.props.page.title}</div>
  }
}

<PageView page={page} />

Functional components[edit | edit source]

import { observer } from 'mobx-react'

const PageView = observer(({page}) => {
  <div>{page.title}</div>
})

<PageView page={page} />

References[edit | edit source]

Credit:rstacruz