Mobx-state-tree create form with types.identifier field on model

789 Views Asked by At

I've started using mobx-state-tree recently and I have a practical question.

I have a model that has a types.identifier field, this is the database id of the resource and when I query for existing stuff it gets populated.

When I am creating a new instance, though, following the example that Michel has on egghead, I need to pass an initial id to my MyModel.create() on initial state, however, this ID will only be known once I post the creation to the API and get the resulting created resource.

I have searched around for a simple crud example using mobx-state-tree but couldn't find one (suggestions?).

What is the best practice here? Should I do a `MyModel.create({ id: 'foobar' }) and weed it out when I post to the API (and update the instance once I get the response from the API)?

1

There are 1 best solutions below

0
On

This is a limitation of mobx-state-tree's current design. Identifiers are immutable.

One strategy I've seen to get around this issue is to store your persistence layer's id in a separate field from your types.identifier field. You would then use a library like uuid to generate the types.identifier value:

import { v4 } from "node-uuid"
const Box = types
    .model("Box", {
        id: types.identifier,
        name: "hal",
        x: 0,
        y: 0
    })
const box = Box.create({ 'hal', 10, 10, id: v4() })