redux-when
Redux middleware for delaying dispatch of an action until a condition evaluates to true.
If you're upgrading from
v0.1.x
make sure you read about the changes introduced inv1.0.0
.
Why
Usually, you use promises to chain asynchronous actions:
/* Save the form and navigate somewhere */const handleFormSubmit = { Promise ;}
But sometimes asynchronous actions have already been dispatched and you don't have a promise to chain on. redux-when
was created to solve this problem:
/* Save the form */const handleFieldBlur = { store}; /* Wait for any save actions to finish and then navigate somewhere */const handleFormSubmit = { store;}
Installation
npm install --save redux-when
Usage
;; const reducer = { }; //create the storeconst store = ; //dispatch the `NAVIGATE` action ONCE the state has been savedstore; //prints: {}console; //dispatch the `SAVE` action which will update the state and trigger// the delayed `NAVIGATE` actionstore; //prints: {saved: true, navigated: true}console;
API
middleware
The Redux middleware.
once(condition, createAction)
Creates an action that will execute ONCE when the condition
evaluates to true.
Parameters:
-
condition : (state : object, action : object) => boolean
— Required. The condition that determines when the action is dispatched. -
createAction : (action : object) => *
— Required. A function creating the action that will be dispatched when thecondition
evaluates totrue
. Can return any value dispatchable by your store including thunks, promises etc as long as your store is configured with the necessary middleware.
Returns:
Returns a dispatchable Redux action that will be handled by the redux-when
middleware. When dispatched, a cancel
token will be returned.
Note: You MUST dispatch the action created by
once()
otherwise nothing will happen.
store;
when(condition, createAction)
Creates an action that will execute EVERY time the condition
evaluates to true.
Parameters:
-
condition : (state : object, action : object) => boolean
— Required. The condition that determines when the action is dispatched. -
createAction : (action : object) => *
— Required. A function creating the action that will be dispatched when thecondition
evaluates totrue
. Can return any value dispatchable by your store including thunks, promises etc as long as your store is configured with the necessary middleware.
Returns:
Returns a dispatchable Redux action that will be handled by the redux-when
middleware. When dispatched, a cancel
token will be returned.
Note: You MUST dispatch the action created by
when()
otherwise nothing will happen.
store;
cancel(token)
Cancels a delayed action created by once()
or when()
.
Parameters:
token : *
— Required. A token returned byonce()
orwhen()
.
Returns:
Returns a dispatchable Redux action that will be handled by the redux-when
middleware. When dispatched, null
will be returned.
Note: You MUST dispatch the action created by
cancel()
otherwise nothing will happen.
;; Component { thistoken = thisprops