Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A node cannot exists twice in the state tree ( mobx-state-tree )

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;
like image 695
su8898 Avatar asked Sep 17 '25 08:09

su8898


1 Answers

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;
like image 104
su8898 Avatar answered Sep 19 '25 23:09

su8898