DEV Community

Daniel Neveux
Daniel Neveux

Posted on • Updated on

Wizar devlog 02: Reference implementation

This week I have refactored my code to implement reference as first class citizen.

Example :

test('references', function() {
  const Item = object({
    id: identifier(), // Set an identifier here.
    price: number(),
  })

  const Player = object({
    inventory: array(Item),
    equipedItem: reference(Item),
  })

  const Fraktar = Player.create({
    inventory: [
      {
        id: '42',
        price: 10,
      },
    ],
    equipedItem: '42',
  })

  // `equipedItem` is a simple string but will be recognized internally as
  // a reference to a node.
  // It will return the item node with the matching identifier.

  expect(Fraktar .equipedItem.price).toBe(10)
})

It is the same system like in Mobx State Tree. Each node of the model tree has an identifier, either given by the factory or generated internaly.

When you hydrate your store with some data which contents some ID. It is easy to reflect the same consistency in the local store. Simply add an identifier type to a field and pass in your document id.

IntelliSense

Code completion is kept between references during code thanks to Typescript.

Alt Text

Next evolution

Mobx State Tree uses reference internally to have better performance on reconciliation. I think I will get a try during the perf optimization iteration.

Also, I will need to add some utilities to make sure references are still alive when used. Or not, maybe it is the dev responsability to check that him/herself.

Top comments (0)