Skip to content

Optional properties in types.model #1921

Answered by Sindr0me
Sindr0me asked this question in Q&A
Discussion options

You must be logged in to vote

If what you're concerned with is the snapshot your model produces you can use a snapshotProcessor to eliminate any undefined properties:

const ConditionalItem = types.snapshotProcessor(
  types.model("ConditionalItem", {
    a: types.maybe(types.string),
    b: types.maybe(types.number),
  }),
  {
    preProcessor: (snap) => snap,
    postProcessor: (snap) =>
      Object.entries(snap).reduce((p, [key, value]) => {
        if (value !== undefined) {
          p[key] = value;
        }
        return p;
      }, {}),
  }
);

const item = ConditionalItem.create({ a: "test" });
console.log(getSnapshot(item)); // { a: "test" }

That is the answer and possible way to do it

Replies: 2 comments 3 replies

Comment options

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

@Ghirigoro
Comment options

@Sindr0me
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by Sindr0me
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