Carlos Mendes
Carlos Mendes

Reputation: 2000

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?

Upvotes: 3

Views: 2460

Answers (1)

Tholle
Tholle

Reputation: 112777

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();

Upvotes: 2

Related Questions