DocsReact ComponentswithModelInjection

withModelInjection

withModelInjection is a higher-order component (HOC) that dynamically injects a model (reducers and epics) into the Redux store at runtime. This is particularly useful for modular applications where models need to be loaded on demand.


Importing

To use withModelInjection, import it from @blue-functor/remodel:

import { withModelInjection } from '@blue-functor/remodel';

Parameters

ParameterTypeRequiredDescription
modelModelYesThe model to be injected, including reducers and epics.

Returns

A higher-order function that wraps a React component to inject the specified model into the Redux store.


Example Usage

src/components/LazyLoadedComponent.tsx
import React from 'react';
import { withModelInjection } from '@blue-functor/remodel';
import userModel from '@/models/users';
 
const LazyLoadedComponent: React.FC = () => {
  return <div>User-specific functionality loaded!</div>;
};
 
export default withModelInjection(userModel)(LazyLoadedComponent);

In this example:

  • The userModel is injected into the Redux store when LazyLoadedComponent is rendered.
  • The LazyLoadedComponent is only displayed after the model is successfully injected.

How It Works

  1. Dynamic Model Injection:

    • The withModelInjection HOC uses the injectModel function to add the model’s reducers and epics to the Redux store dynamically.
  2. Store Access:

    • It uses react-redux’s useStore hook to access the Redux store.
  3. Subscription Handling:

    • The component ensures that the model is fully injected before rendering the wrapped component. Until the injection is complete, it renders null.
  4. State Management:

    • A local hasSubscribed state is used to track when the injection process has finished, ensuring the component only renders after the model is ready.

Notes

  • withModelInjection is ideal for lazy-loading models in modularized or large-scale applications.
  • The wrapped component will not render until the model is successfully injected, ensuring consistency and avoiding potential race conditions.
  • The model parameter must adhere to the Model type, which includes the required reducers and epics for dynamic injection.