I'm getting an error that says Error: [mobx-state-tree] A node cannot exists twice in the state tree. Failed to add SearchModel@/results/0 to path '/selectedItem'
when assigning a value to selectedItem
in the following model via the setSelectedItem
action. I've checked the documentation and I'm not sure what's causing this issue.
Appreciate any help. thanks!
const SearchModel = types
.model({
results: types.array(ItemModel, []),
selectedItem:types.maybeNull(ItemModel,{ id: 0 })
})
.actions(self => ({
setSelectedItem(selItem) {
console.log( 'typeof(selItem)', typeof(selItem));
self.selectedItem=selItem;
}
}));
export default SearchModel;
For anyone looking for a solution to this type of an error in future, I've used the spread operator to assign a shallow copy of selItem
to self.selectedItem
and the problem went away.
The code had to look as follows:
const SearchModel = types
.model({
results: types.array(ItemModel, []),
selectedItem:types.maybeNull(ItemModel,{ id: 0 })
})
.actions(self => ({
setSelectedItem(selItem) {
self.selectedItem = { ...selItem };
}
}));
export default SearchModel;