Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a deep copy of a mobx class with observables and computeds?

I want to create a deep copy of an object that has mobx observable and computed properties.

The goal is to create copy item for local editing, that can be committed or discarded.

I've found an example of this behavior but it is from mobx-state-tree:

enter image description here

How can I achieve the same behaviour in mobx?

like image 456
Carlos Mendes Avatar asked Dec 09 '25 01:12

Carlos Mendes


1 Answers

You can use the createViewModel from the mobx-utils package.

Example

class Todo {
  @observable firstName = "Foo";
  @observable lastName = "Bar";
  @computed get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const todo = new Todo();
const todoCopy = createViewModel(todo);

todoCopy.firstName = "Baz";

// ...

// Submit the changes to the original todo
todoCopy.submit();
like image 80
Tholle Avatar answered Dec 11 '25 22:12

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!