API
- withInitAction
([initProps], initAction, [options])(Component) - withInitAction
([initProps], initAction, [options])(componentId)(Component)advanced - prepareComponent
(Component, props) - prepareComponents
(components, props) - setInitMode
(initMode)
withInitAction ([initProps], initAction, [options])(Component)
Higher-order component that adds an init action to an existing component.
Arguments
initProps: Array<string> optional
An array of names of React props that your init action depends on
- On component mount, a value is required for each of these props
- The values for these props need to be provided to
prepareComponent()(see basic usage) - By default the component will “re-initialize” if these props change value on the client. See
reinitializeinoptionsbelow - Dot notation can be used to define a subset of an object prop. For example, when using
['foo.bar', 'foo.foobar']theinitActionwill only get the propertiesbarandfoobaron thefooprop. (see using init props)
initAction: Function | { [clientOnly]: Function, [prepared]: Function }
This is the actual initialization function with signature (props, dispatch, getState) => Promise
- basic usage For regular init actions you can pass a single function here.
- client-only If some part of you init action needs to be executed on client-side only, you can pass an object with the client-side initialization function on the
clientOnlyproperty, and (optionally) the server prepared initialization on thepreparedproperty.
The function(s) must return a Promise that resolves when initialization is complete. The following arguments are passed:
props: ObjectAn object containing values of the props defined ininitProps. IfinitPropsis not defined, this is an empty object.dispatch: FunctionThe Redux dispatch function. This can be used to dispatch your redux actions or dispatch theprepareComponent()action for child componentsgetState: FunctionThe Redux getState function.
options: Object optional
An object with additional options.
reinitializeIftrue, will callinitActionagain if any of the props defined ininitPropschange after mount. This change is checked with strict equality (===) Defaults totrueinitSelfA string that indicates the behavior for initialization on the client (initMode == MODE_INIT_SELF). See an example usage below. Possible values:INIT_SELF_ASYNC="ASYNC"default
the component will render immediately, even ifinitActionis still pending. It is recommended to use this option and render a loading indicator or placeholder content untilinitActionis resolved. This will give the user immediate feedback that something is being loaded. While theinitActionis pending, anisInitializingprop will be passed to the component.INIT_SELF_BLOCKING="BLOCKING"
this will cause this higher-order component not tot mount the target component until the first initialization has completed. The component will remain mounted during further re-initialization.INIT_SELF_UNMOUNT="UNMOUNT"
same asINIT_SELF_BLOCKINGbut it will also unmount the component during re-initialization.INIT_SELF_NEVER="NEVER"
will only initialize on the server (initMode == MODE_PREPARE). Initialization will be skipped on the client.
onErrorError handler for errors ininitAction. If given, errors will be swallowed.getPrepareKey: (componentId: string, propsArray: Array) => stringA function that generates a “prepare key” that will be used to uniquely identify a component and its props. It has the following signature: This defaults to a function that concatenates thecomponentIdand the stringifiedpropsArray. In most cases, this will ensure that a component instance on the server is matched to the corresponding instance on the client. However, if the props are somehow always different between server and client, you may use this function to generate a key that omits that difference.getInitStateA function that takes the Redux state and returns the init state of the reducer from this module. By default, it is assumed the state is under theinitproperty. If the reducer is included elsewhere, this function can be set to retrieve the state.allowLazyadvanced In most cases you want to use theclientOnlyproperty ininitActionto defer initialization to the client (see client-only init actions). Use this option if you have an init action that sometimes needs to be deferred to the client, and sometimes prepared on the server. Iftrue, callingprepareComponent()for thepreparedinit action becomes optional. If you do not prepare the component, no error will be thrown and initialization is automatically deferred to the client. This has no effect on anyclientOnlyinit actions. Defaults tofalse
Returns function
Returns a function that can be used to add the init action to a component. The function will return a new component. See Higher-Order Components
example
// Post.js
import { withInitAction, INIT_SELF_BLOCKING } from 'react-redux-component-init';
import { loadPostData } from '../actions/api';
class Post extends React.Component {
// ...
}
export default withInitAction(
['id'],
({ id }, dispatch) => dispatch(loadPostData(id)),
{ initSelf: INIT_SELF_BLOCKING }
)(Post);
// PostPage.js
import { withInitAction, prepareComponent } from 'react-redux-component-init';
import Post from './components/Post';
// ...
class PostPage extends React.Component {
// ...
render() {
// ...
<Post id={this.props.location.query.postId} />
// ...
}
}
export default withInitAction(
['location.query'],
({ location: { query } }, dispatch) => dispatch(prepareComponent(Post, { id: query.postId }))
)(PostPage);
withInitAction ([initProps], initAction, [options])(componentId)(Component) advanced
You can pass a custom component id to withInitAction. Normally the component id is derived from the displayName of the component (or if that does not exist, the .name property). This id is supposed to be unique, because it is used internally to reference which components have been prepared. If for whatever reason your component does not have a name or does not have a unique name, you can use this syntax of withInitAction to pass a custom name.
API is otherwise identical to withInitAction
example
class Post extends React.Component {
// ...
}
// Regular usage, component id will be 'Post'
export default withInitAction(
(props, dispatch) => dispatch(loadPostData()),
{ initSelf: INIT_SELF_BLOCKING }
)(Post);
// Custom component id, component id will be 'Custom'
export default withInitAction(
(props, dispatch) => dispatch(loadPostData()),
{ initSelf: INIT_SELF_BLOCKING }
)('Custom')(Post);
prepareComponent (Component, props)
Arguments
Action to prepare a component for rendering on the server side (initMode == MODE_PREPARE). Should be passed to the Redux dispatch function. Returns a Promise that resolves when preparation is complete
Component: react.Component
The component that should be prepared. This should be a component returned by the withInitAction higher-order component. If Component has no withInitAction wrapper or only has a clientOnly action, dispatching this action will have no effect.
props: object
The props to prepare the component with. These should be the same props as you expect to pass when you eventually render component. It should at least include the props configured in the initProps array of withInitAction. Duplicate calls to prepareComponent() with the same Component and props will be ignored.
Example
dispatch(prepareComponent(MyComponent, { id: 45 }))
prepareComponents (components, props)
A shorthand action creator for multiple prepareComponent() calls with the same props. Returns a Promise that resolves when preparation for all components is complete
Arguments
components: Array<react.Component>
An array of components to prepare
props: object
The props to prepare with. See prepareComponent()
Example
dispatch(prepareComponents([SomeComponent, OtherComponent], { id: 45 }))
setInitMode (initMode)
An action to switch the initMode of the application. Should be called with MODE_INIT_SELF after the initial render on the client.
Arguments
initMode: string
Either of the modes MODE_PREPARE or MODE_INIT_SELF as defined in the exports of this module
Example
import { initMode, MODE_INIT_SELF } from 'react-redux-component-init';
// ...
dispatch(setInitMode(MODE_INIT_SELF));