Skip to content

Confused on which type(s) to use when how to store a large object with dynamic keys #1893

Answered by EmilTholin
andrewdang17 asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @andrewdang17!

Normalization is often nicely handled with the help of references.

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

const Todo = types.model({
  id: types.identifierNumber,
  name: types.string
});
const RootStore = types.model({
  todoIds: types.array(types.reference(Todo)),
  todos: types.map(Todo),
  selectedTodo: types.reference(Todo)
});

const rootStore = RootStore.create({
  todoIds: [1, 2, 3],
  todos: {
    1: { id: 1, name: "Foo" },
    2: { id: 2, name: "Bar" },
    3: { id: 3, name: "Baz" }
  },
  selectedTodo: 1
});

// References are evaluated to their corresponding model instance
console.log(rootStore.selectedTodo)
// => {id: 1, name: "Foo"}
console.log(rootStore.t…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@andrewdang17
Comment options

@andrewdang17
Comment options

@EmilTholin
Comment options

Answer selected by andrewdang17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1892 on March 30, 2022 17:00.