Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 479
Lil E Avatar asked Oct 17 '25 16:10

Lil E


1 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.

like image 167
Will Avatar answered Oct 22 '25 04:10

Will