Skip to content

withLazyViewModel HOC

DEPRECATED

This HOC will be removed after 2-3 next major releases since 8.x.x.
Better to use loadable() HOC from react-simple-loadable package instead.

Reason of the deprecation:
This HOC is requires you to load model and view modules separately. So they will be loaded as separated chunks.
This solution is not good and gives no benefits.

Optional for usage HOC that doing the same thing as withViewModel, but fetching ViewModel and View "lazy"

API Signature

tsx
function withLazyViewModel<TViewModel extends AnyViewModel>(
  loadFn: () => Promise<{
    Model: Class<TViewModel> | Promised<Class<TViewModel>>,
    Component: TView | Promised<TView>
  }>,
  config?: ViewModelHocConfig<TViewModel>
): VMLazyComponent

Usage

Let's create a ViewModel with a lot blocks of code

ts
import { ViewModelBase } from "mobx-view-model";

export class FruitButtonHugeVM extends ViewMOdelBase {
  ... // large of code lines

  handleButtonClick = () => {
    //...
  }
}

Create a View component

tsx
import { ViewModelProps } from "mobx-view-model";
import { observer } from "mobx-react-lite";
import { FruitButtonHugeVM } from "./model";

export const FruitButtonView = observer(({
  model
}: ViewModelProps<FruitButtonHugeVM>) => {
  return (
    <div>
      <button onClick={model.handleButtonClick}>click me</button>
    </div>
  )
})

And connect them together with lazy loading this modules using this HOC

tsx
import { withLazyViewModel } from "mobx-view-model";

export const FruitButton = withLazyViewModel(() => {
  return {
    Model: import("./model").then(m => m.FruitButtonHugeVM),
    View: import("./view").then(m => m.FruitButtonView),
  }
})

Also you can use "default" exports if you need

tsx
... // model.ts
export default class MyVM extends ViewModelBase {}
... // view.tsx
export default function MyView() { return <div>1</div> }
... // index.ts
export const MyComponent = withLazyeViewModel(() =>{
  return {
    Model: import("./model"),
    View: import("./view"),
  }
})

Released under the MIT License.