Create Relationships in your Data with mobx-state-tree Using References and Identifiers

Share this video with your friends

Send Tweet

MST stores all data in a tree, where each piece of data lives at one unique location. In most state management solutions, this means you need to introduce weakly typed, primitive 'foreign keys' to refer to other parts of the state tree. But in MST you can leverage the concepts of references and identifiers to relate model instances to each other. MST will do the normalization behind the scenes for you.

In this lesson you will learn:

  • The use of types.identifier to uniquely identify an instance of a specific type
  • The use of types.reference to refer to data in another part of the tree, and with which you can interact with in another part of the tree
  • The use of types.maybe to make as ".. or null" type
  • Using types.late to create circular type definitions
Gar Liu
Gar Liu
~ 3 years ago

Hello Michel. I understand what types.optional is but not too sure about types.maybe. What is the difference between the 2?

Michel Weststrate
Michel Weststrate(instructor)
~ 3 years ago

optional means that the value can be left out of the snapshot, in which case it will fall back to the default. Maybe means that 'null' is itself is an acceptable value for that property. So x: types.optional(types.number, 3) means that "x" is always a number, and 3 if not provided. in contrast x: types.maybe(types.number) means that "x" might be a number, but it might also be "null"

Op do 29 mrt. 2018 om 18:15 schreef Gar notifications@egghead.io:

Gar Liu
Gar Liu
~ 3 years ago

Is

types.optional(types.number, null);

the same as

types.maybe(types.number);

Michel Weststrate
Michel Weststrate(instructor)
~ 3 years ago

The the first is is an invalid type; null is not assignable to a number. So the default you pass to optional should be valid for the type you are trying to make optional

Op do 29 mrt. 2018 om 19:50 schreef Gar notifications@egghead.io:

Gar Liu
Gar Liu
~ 3 years ago

Ok. I get it. If i need to assign null then use maybe.

Maung San
Maung San
~ 5 months ago

Can you please show code snippet on how to test a model that has references to another model(or) has reference to itself? For example, the user model that is used in the video.

const User = types
    .model({
        id: types.identifier,
        name: types.string,
        gender: types.enumeration("gender", ["m", "f"]),
        wishList: types.optional(WishList, {}),
        recipient: types.maybe(types.reference(types.late(() => User))),
    })

Thanks in advance!