Mobx model type for hashmap

522 Views Asked by At

I want my model variable to look like

  {
    "foo": {
      "viewed": false,
      "url": "https://www.google.com"
    },
    "bar": {
      "viewed": false,
      "url": "https://www.google.com"
    },
    "baz": {
      "viewed": false,
      "url": "https://www.google.com"
    }
  }

I have a separate model like this

import { types as t } from "mobx-state-tree"

export const deviceInstruction = t.model({
  viewed: t.boolean,
  url: t.string
})

type DeviceInstructionType = typeof deviceInstruction.Type

export interface IDeviceInstruction extends DeviceInstructionType {}

And was hoping to something like

export const exampleStore = t
  .model({
    devices: t.optional(deviceInstruction), {}),
    })

But that doesn't work. I'm not sure how to situate it so it has the proper key. Thanks for your help

1

There are 1 best solutions below

0
On

Object literals fits nicely with a map:

import { types as t } from "mobx-state-tree";

const DeviceInstruction = t.model({
  viewed: t.boolean,
  url: t.string
});

const ExampleStore = t.model({
  devices: t.map(DeviceInstruction)
});

const exampleStore = ExampleStore.create({
  devices: {
    foo: {
      viewed: false,
      url: "https://www.google.com"
    },
    bar: {
      viewed: false,
      url: "https://www.google.com"
    },
    baz: {
      viewed: false,
      url: "https://www.google.com"
    }
  }
});

console.log(exampleStore.devices.get("foo"));
// { viewed: false, url: "https://www.google.com" }