MobX

MobX

  • API Reference
  • 中文(寻求翻译)
  • Sponsors
  • GitHub

›Tips & Tricks

Introduction

  • README
  • About this documentation
  • Installation
  • The gist of MobX

MobX core

  • Observable state
  • Actions
  • Computeds
  • Reactions {🚀}

MobX and React

  • React integration
  • React optimizations {🚀}

Tips & Tricks

  • Defining data stores
  • Understanding reactivity
  • Subclassing
  • Analyzing reactivity {🚀}
  • Computeds with arguments {🚀}
  • MobX-utils {🚀}
  • Custom observables {🚀}
  • Lazy observables {🚀}
  • Collection utilities {🚀}
  • Intercept & Observe {🚀}

Fine-tuning

  • Configuration {🚀}
  • Enabling decorators {🚀}
  • Migrating from MobX 4/5 {🚀}
Edit

Collection utilities {🚀}

They enable manipulating observable arrays, objects and Maps with the same generic API. These APIs are fully reactive, which means that even without Proxy support new property declarations can be detected by MobX if set is used to add them, and values or keys are used to iterate over them.

Another benefit of values, keys and entries is that they return arrays rather than iterators, which makes it possible to, for example, immediately call .map(fn) on the results.

All that being said, a typical project has little reason to use these APIs.

Access:

  • values(collection) returns an array of all the values in the collection.
  • keys(collection) returns an array of all the keys in the collection.
  • entries(collection) returns an array of all the entries [key, value] pairs in the collection.

Mutation:

  • set(collection, key, value) or set(collection, { key: value }) update the given collection with the provided key / value pair(s).
  • remove(collection, key) removes the specified child from the collection. Splicing is used for arrays.
  • has(collection, key) returns true if the collection has the specified observable property.
  • get(collection, key) returns the child under the specified key.

If you use the access APIs in an environment without Proxy support, then also use the mutation APIs so they can detect the changes.

import { get, set, observable, values } from "mobx"

const twitterUrls = observable.object({
    Joe: "twitter.com/joey"
})

autorun(() => {
    // Get can track not yet existing properties.
    console.log(get(twitterUrls, "Sara"))
})

autorun(() => {
    console.log("All urls: " + values(twitterUrls).join(", "))
})

set(twitterUrls, { Sara: "twitter.com/horsejs" })
← Lazy observables {🚀}Intercept & Observe {🚀} →
MobX
Docs
About MobXThe gist of MobX
Community
GitHub discussions (NEW)Stack Overflow
More
Star