You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api/view-models/view-model-simple.md
+51-9Lines changed: 51 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -10,13 +10,6 @@ Use `ViewModelSimple` when:
10
10
2. You prefer a simple, boilerplate-free class structure
11
11
3. Your view model does not required advanced features like [`viewModels` access](/api/view-models/base-implementation.html#viewmodels) or complex lifecycle hooks.
12
12
13
-
## Implementation
14
-
15
-
### Requirements
16
-
To implement `ViewModelSimple`, your class must:
17
-
1. Define a unique `id` property to identify the instance (used for access in `ViewModelStore`)
18
-
19
-
20
13
### Example
21
14
```ts
22
15
import { ViewModelSimple } from"mobx-view-model";
@@ -41,11 +34,58 @@ export class FruitViewModel implements ViewModelSimple {
41
34
}
42
35
```
43
36
37
+
::: tip defining `id` property is optional
38
+
If you do not define the `id` property, a random id will be generated from `viewModelsConfig.generateId`
39
+
:::
40
+
41
+
### Example without any implemented method from interface
42
+
43
+
```ts{4}
44
+
import { ViewModelSimple } from "mobx-view-model";
45
+
import { makeAutoObservable } from "mobx";
46
+
47
+
export class FruitViewModel {
48
+
// Observable state
49
+
fruit = "apple";
50
+
51
+
constructor() {
52
+
// Initialize MobX observables
53
+
makeAutoObservable(this);
54
+
}
55
+
56
+
// Example action
57
+
setFruit(newFruit: string) {
58
+
this.fruit = newFruit;
59
+
}
60
+
}
61
+
```
62
+
63
+
::: tip `implements ViewModelSimple` was removed
64
+
Because TypeScript throws an error about not implementing at least one property or method of the `ViewModelSimple` interface.
65
+
:::
66
+
44
67
## Usage in React
45
68
46
-
### Instance creation
69
+
### Usage with [`withViewModel`](/react/api/with-view-model) HOC
47
70
48
-
Create instances using the [`useCreateViewModel`](/react/api/use-create-view-model) hook. This ensures proper lifecycle management and reactivity:
71
+
```tsx
72
+
import { observer } from"mobx-react-lite";
73
+
import { withViewModel } from"mobx-view-model";
74
+
import { FruitViewModel } from"./model";
75
+
76
+
exportconst FruitComponent =withViewModel(FruitViewModel, ({ model }) => {
77
+
return (
78
+
<div>
79
+
<p>Current fruit: {model.fruit}</p>
80
+
<buttononClick={() =>model.setFruit("banana")}>
81
+
Change to Banana
82
+
</button>
83
+
</div>
84
+
);
85
+
});
86
+
```
87
+
88
+
### Usage with [`useCreateViewModel`](/react/api/use-create-view-model) hook
0 commit comments