Skip to content

With base implementation

Another simplest usage is to work with base implementation of the ViewModel interface

Steps:

  1. Create your ViewModel class using ViewModelBase (base implementation of ViewModel 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();
  }
}
  1. 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>;
  },
);
  1. 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

Released under the MIT License.