With base implementation
Another simple usage is to work with the base implementation of the ViewModel interface.
Follow the steps:
1. Create your ViewModel class using ViewModelBase (base implementation of ViewModel package interface)
tsx
import { observable } from 'mobx';
import { ViewModelProps, ViewModelBase, withViewModel } from 'mobx-view-model';
export class MyPageVM extends ViewModelBase<{ payloadA: string }> {
@observable
accessor state = '';
mount() {
super.mount();
}
protected didMount() {
console.info('did mount');
}
unmount() {
super.unmount();
}
}2. Create view component using HOC withViewModel()
tsx
import { withViewModel } from 'mobx-view-model';
export const MyPage = withViewModel(MyPageVM, ({ model }) => {
return <div>{model.state}</div>;
});or you can use the useCreateViewModel() hook
tsx
import { observer } from 'mobx-react-lite';
import { ViewModelPayload, useCreateViewModel } from 'mobx-view-model';
export const MyPage = observer(
({ payload }: { payload: ViewModelPayload<MyPageVM> }) => {
const model = useCreateViewModel(MyPageVM, payload);
return <div>{model.state}</div>;
},
);don't forget to use the observer() hoc
3. Use it
tsx
<MyPage payload={{ payloadA: '1' }} />If you need access to other view models, then you need to add a ViewModelStore.
You can find that guide on the next page.
