-
Imagine we have a list of units: export const unitModel = types.model({
id: types.identifier,
name: types.string,
}) Now on a product entity we need to map some units to weights: export const productModel = types.model({
id: types.identifier,
name: types.string,
servings: types.array(types.model({
unit: types.reference(unitModel),
weight: types.number,
}))
}) The obvious problem with this approach is that array can have more than one same unit. It would be better to use unit.id as indices, like what I don't find an appropriate type to achieve this right now. Maybe I'm missing something? I'd imagine that a new type could do what such operation suggests: mapping a set of things to a set of other things. E.g. servings: types.mapWithProps(unitModel, type.model({...}))
// Or
servings: types.mapTo(unitModel, type.model({...})) Ideas? WorkaroundCurrently I'm gonna use something like this: ...
servings: types.map(
types.model({
unit: types.reference(unitModel),
weight: types.number,
})
),
})
.actions((self) => ({
addServing(unit: Instance<typeof unitModel>, weight: number) {
self.servings2.set(unit.id, { unit, weight })
}, for what it's worth |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
I'm not sure I understand the issue you're describing. If I do this: import { getSnapshot, types } from "mobx-state-tree";
export const unitModel = types.model({
id: types.identifier,
name: types.string,
});
export const productModel = types.model({
id: types.identifier,
name: types.string,
servings: types.array(
types.model({
unit: types.reference(unitModel),
weight: types.number,
})
),
});
const StoreModel = types.model({
units: types.array(unitModel),
product: productModel,
});
const store = StoreModel.create({
units: [
{ id: "1", name: "1" },
{ id: "2", name: "2" },
],
product: {
id: "1",
name: "product",
servings: [
{
unit: "1",
weight: 1,
},
{
unit: "1",
weight: 2,
},
{
unit: "2",
weight: 3,
},
],
},
});
console.log("first serving, unit 1");
console.log(store.product.servings[0].unit); // logs out the { id: '1', name: '1' }
console.log("second serving, unit 1");
console.log(store.product.servings[1].unit); // logs out { id: '1', name: '1' }
console.log("third serving, unit 2");
console.log(store.product.servings[2].unit); // logs out { id: '2', name: '2' } What do you want to happen instead? |
Beta Was this translation helpful? Give feedback.
Ok, I investigated this further a little and this is what I got.
MobX supports objects as keys. E.g. this is ok:
so we index servings map with unit objects.
We could also do this:
Looks like
sugar.servings
becomes an indirectobservable.map
.However, when it comes to mobx-state-tree, we cannot use objects to index maps: