What's the difference between model and props in `mobx-state-tree`?

Viewed 689

It seems to me that people are using model and props interchangeably. I try to find documents about props but failed. Could someone tell me the difference?

2 Answers

The model method creates a new model. It takes two parameters:

  • name
  • properties (optional)

You can create a new model and specify the properties. Or you can create the model first and then 'extend' it with the props method (props is short for properties). TodoOne and TodoTwo are the same.

const TodoOne = types.model("Todo", {title: types.string, done: types.boolean})

const TodoTwo = types.model("Todo")
  .props({
    title: types.string, 
    done: types.boolean
  }) 

But how is this useful? Well the props method doesn't mutate the current type it creates a new one and extends it. This means that we can add or override existing props.

const Todo = types.model("Todo", {title: types.string, done: types.boolean})

const ColorfulTodo = Todo.props({color: types.string}) // returns a new model with a new property

const DefaultTodo = Todo.props({done: false}) // returns a new model with done property overwritten to default to false

The views and actions methods can extend models in same way as the props method.

Model needs properties.

const Todo = types
    .model("Todo", {
        title: types.string,
        done: false
    })

In the example above we created a Todo model (MST model) with two properties:

title which is a String

done witch is a Boolean and defaults to false

So when you hear props they are referring to the properties of the model.

Related