mobx-view-model
Version:
MobX ViewModel power for ReactJS
41 lines (40 loc) • 1.63 kB
JavaScript
import { loadable } from 'react-simple-loadable';
import { unpackAsyncModule } from 'yummies/imports';
import { viewModelsConfig } from '../config/global-config.js';
import { withViewModel, } from './with-view-model.js';
/**
* A Higher-Order Component that **LAZY** connects React components to their ViewModels, providing seamless MobX integration.
*
* [**Documentation**](https://js2me.github.io/mobx-view-model/react/api/with-lazy-view-model.html)
*/
export function withLazyViewModel(loadFunction, configOrFallbackComponent) {
const config = typeof configOrFallbackComponent === 'function'
? {
fallback: configOrFallbackComponent,
}
: configOrFallbackComponent;
const patchedConfig = {
...config,
ctx: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
...config?.ctx,
externalComponent: null,
},
};
const fallbackComponent = patchedConfig?.fallback ?? viewModelsConfig.fallbackComponent;
const lazyVM = loadable(async () => {
const { Model: ModelOrAsync, View: ViewOrAsync } = await loadFunction();
const [Model, View] = await Promise.all([
unpackAsyncModule(ModelOrAsync),
unpackAsyncModule(ViewOrAsync),
]);
return withViewModel(Model, patchedConfig)(View);
}, {
loading: patchedConfig?.loading ?? fallbackComponent,
preload: patchedConfig?.preload,
throwOnError: patchedConfig?.throwOnError,
});
patchedConfig.ctx.externalComponent = lazyVM;
return lazyVM;
}