Repository navigation
Using the make(auto)Observable api to make an already created instance of a class reactive #4579
|
Hello, I want to create a domain model separated from the reactive library, and after it is created, I want to make it reactive. As far as I know, the MobX documentation recommends using make(auto)observable inside the class constructor, but it doesn’t prohibit using this API on an already created object (including non-plain objects with a prototype different from Object). What other ways are there to make a class instance reactive from the outside, apart from make(auto)observable? And is using make(auto)observable the normal way to achieve my goal? I mean this: |
Replies: 1 comment
|
Yes, Here's an example with a pure domain class made reactive after creation: import { makeAutoObservable } from 'mobx';
class UserModel {
name = 'Alice';
age = 30;
get isAdult() {
return this.age >= 18;
}
setAge(newAge: number) {
this.age = newAge;
}
}
// 1. Plain domain instance without MobX dependencies
const user = new UserModel();
// 2. Make the existing instance reactive
makeAutoObservable(user);Keep in mind
|
Yes,
makeObservableandmakeAutoObservableboth accept any object or class instance at any point after creation. You don't have to call them inside the constructor.Here's an example with a pure domain class made reactive after creation:
Keep in mind
makeObservableormakeAutoObservabletwice on the sa…