Skip to content
⚠️You are viewing an older version. Switch to the latest version (v11.x).View latest →

Using all props as payload for your ViewModel ​

This recipe is helpful if you want to use all props as payload (this.payload) in your ViewModel.

What you will need:

What you will do:

  • Pass props type into first generic type parameter in ViewModelBase class
  • Configure withViewModel HOC with getPayload function that returns all props as payload
  • Override type of output React component into fixed type
tsx
import { ViewModelBase } from 'mobx-view-model';
import { withViewModel } from 'mobx-view-model-react';

interface ComponentProps {
  foo: number;
}

class YourVM extends ViewModelBase<ComponentProps> {
  
}

export const YourComponent = withViewModel(
  YourVM, 
  ({ model }) => {
    return (
      <div>{model.payload.foo}</div>
    )
  },
  {
    getPayload: (props) => props
  }
) as unknown as ComponentType<ComponentProps>

...

<YourComponent foo={1} />