Why do I get this error, because I use different stores?
Source:
const Shop = types.model('Shop', {
id: types.identifier(types.number),
coordinates: types.array(types.number),
});
const MapScreenStore = types.model('MapScreenStore', {
shops: types.optional(types.map(Shop), {}),
}).actions(self => ({
setShops(shops) {
self.shops.clear();
for (const shop of shops) {
self.shops.set(shop.id, shop);
}
},
}));
const ApplicationStore = types.model('ApplicationStore', {
selectedShop: types.maybe(Shop),
}).actions(self => ({
selectShop(shop) {
self.selectedShop = shop;
},
}));
const appStore = ApplicationStore.create();
const mapStore = MapScreenStore.create();
mapStore.setShops([
{ id: 1, coordinates: [0, 0] },
{ id: 2, coordinates: [132.254345, 42.434764] },
{ id: 3, coordinates: [128.234566, 43.234235] },
]);
appStore.selectShop(mapStore.shops.get(1));
console.log(toJS(appStore.selectedShop));
Error:
A node cannot exists twice in the state tree. Failed to add Shop@/shops/1(id: 1) to path '/selectedShop'.
id (initialized with types.identifier that is) has to be unique across the whole tree. Try types.reference instead of directly assigning the node.
const ApplicationStore = types.model('ApplicationStore', {
selectedShop: types.maybe(types.reference(Shop)),
}).actions(self => ({
selectShop(shop) {
self.selectedShop = shop;
},
}));
Does MST always have a global tree of states? When I create a node it registers in the global tree?
Hm... actually it wasn't apparent from your snippet if those stores were part of the global tree (your own one that you define in some other module for example) or not, so I've assumed that they are. Do you say that those stores are separate and you still observe a conflict between them?
Yes, I have separate stores
As the error suggests, no MST object can be part of two different trees at the same time.
Please reopen and set up a running reproduction in a code sandbox if you have follow up questions
Most helpful comment
id(initialized withtypes.identifierthat is) has to be unique across the whole tree. Try types.reference instead of directly assigning the node.