Do we have something like a collection type (not array type) or serialize model #1867
-
In our project, we heavily use An example will make the Issue easier to understand Our data structure looks like this
Because of that, our MST model looks like this.
The Issue: our Our workaround: create The reason why we are not fans of this workaround is that it affects the final JSON output now, it will look like this:
Is there an easy way to create collection models without creating extra properties? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @nadeemkhedr! If the big turnoff for the second approach you outline in your question is the changed JSON output, you could add a custom Example import { getSnapshot, types } from "mobx-state-tree";
const modelToArrProcessor = {
// from snapshot to instance
preProcessor(snapshot) {
return {
arr: snapshot
};
},
// from instance to snapshot
postProcessor(instance) {
return instance.arr;
}
};
const Type1 = types.model({
id: types.identifier
});
const ArrayType1Collection = types.snapshotProcessor(
types
.model({
arr: types.array(Type1)
})
.views((self) => ({
// multiple views for Type1
}))
.actions((self) => ({
// multiple actions for Type1
})),
modelToArrProcessor
);
const Type2 = types.model({
id: types.identifier
});
const ArrayType2Collection = types.snapshotProcessor(
types
.model({
arr: types.array(Type2)
})
.views((self) => ({
// multiple views for Type2
}))
.actions((self) => ({
// multiple actions for Type2
})),
modelToArrProcessor
);
const CollectionModel = types.model("SceneModel", {
arrayType1Collection: ArrayType1Collection,
arrayType2Collectiony: ArrayType2Collection
});
const collectionModel = CollectionModel.create({
arrayType1Collection: [],
arrayType2Collectiony: []
});
console.log(getSnapshot(collectionModel));
// { arrayType1Collection: [], arrayType2Collectiony: [] } |
Beta Was this translation helpful? Give feedback.
Hi @nadeemkhedr!
If the big turnoff for the second approach you outline in your question is the changed JSON output, you could add a custom
snapshotProcessor
to have separate models for your views and actions, but have the JSON output be just arrays.Example