useViewModel
hook
A hook that provides access to an already created ViewModel instance within a React component.
If you need to create instance of ViewModel
Please use hook useCreateViewModel
or HOC withViewModel
API Signature
tsx
function useViewModel<VM extends AnyViewModel>(): VM
function useViewModel<VM extends AnyViewModel>(vmLookup: ViewModelLookup<VM>): VM
Usage
1. Basic Usage
Requires withViewModel()
HOC usage to access
Reference to the last created ViewModel instance based on React
tree
Use generic type (YourVM
) to define type of returning view model instance
tsx
import { observer } from "mobx-react-lite";
export const YourComponent = observer(() => {
const yourVM = useViewModel<YourVM>();
});
2. Precise search with ViewModelLookup
Requires ViewModelStore
This variant requires connected ViewModelStore
to your React application using <ViewModelsProvider />
HOC
Use argument vmLookup
to define specific identifier of returning ViewModel instance and generic for the same as above usage
tsx
import { observer } from "mobx-react-lite";
export const YourComponent = observer(() => {
const yourVM = useViewModel<YourVM>('view-model-id');
});