Search code examples
mobxmobx-state-tree

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?


Solution

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