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
| Parameter | Type | Required | Description |
|---|---|---|---|
model | Model | Yes | The 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
userModelis injected into the Redux store whenLazyLoadedComponentis rendered. - The
LazyLoadedComponentis only displayed after the model is successfully injected.
How It Works
-
Dynamic Model Injection:
- The
withModelInjectionHOC uses theinjectModelfunction to add the model’s reducers and epics to the Redux store dynamically.
- The
-
Store Access:
- It uses
react-redux’suseStorehook to access the Redux store.
- It uses
-
Subscription Handling:
- The component ensures that the model is fully injected before rendering the wrapped component. Until the injection is complete, it renders
null.
- The component ensures that the model is fully injected before rendering the wrapped component. Until the injection is complete, it renders
-
State Management:
- A local
hasSubscribedstate is used to track when the injection process has finished, ensuring the component only renders after the model is ready.
- A local
Notes
withModelInjectionis 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
modelparameter must adhere to theModeltype, which includes the required reducers and epics for dynamic injection.