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