Mobx State Tree Resource

This resource will provide guides to leveraging Mobx State Tree. This is not final and will be updated periodically.

Extending

  • Create a base model for your application. These actions could include the typical CRUD create, read, update, delete.

  • Ensure types are extended so you can define component properties.

import { useEffect } from "react";
import { Instance, types } from "mobx-state-tree";

export const Model = types
  .model("Model")
  .props({
    id: types.identifier,
    // ...
  })
  .views((self) => {
    return {
      get displayName() {
        return self.id;
      },
    };
  })
  .actions((self) => {
    return {
      save() {
        console.log("saving...");
      },
    };
  });

export type ModelType = Instance<typeof Model>;

export const ItemModel = types.compose(
  Model,
  types
    .model("ItemModel", {
      // id extend...
      first: types.maybe(types.string),
      last: types.maybe(types.string),
    })
    .views((self) => {
      return {
        get displayName() {
          return `${self.first} ${self.last}`;
        },
      };
    })
    .actions((self) => {
      return {
        customAction() {
          console.log("custom action...");
        },
      };
    })
);

export type ItemModelType = Instance<typeof ItemModel> & ModelType;

// example usage
const item = ItemModel.create({ id: "1", first: "John", last: "Doe" });
item.displayName;
item.save();
item.customAction();

// example component with type reference
export const Component = ({ model }: { model?: ItemModelType }) => {
  useEffect(() => {
    model?.save();
    model?.customAction();
  }, []);
  return <div>model?.displayName</div>;
};