redux-ondispatch
v1.0.0
Published
Redux Middleware that supports executing the function assigned to an action's onDispatch property when the action is dispatched
Downloads
6
Readme
redux-ondispatch
redux-ondispatch is middleware that allows you to include a function to be executed when a redux action is dispatched. Eg:
function myAjaxAction(id) {
return {
type: FETCH_SOMETHING,
payload: { id },
onDispatch: (store, action) => {
fetch(`/api/something/${action.payload.id}`)
.then((something) => {
store.dispatch({
type: SOMETHING_FETCHED,
something
});
});
}
};
}
store.dispatch(myAjaxAction(1));
Usage
Requirements:
redux
Install the package via npm or yarn
> npm install redux-ondispatch
or
> yarn add redux-ondispatch
- Define the middleware as part of your redux store
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers'; // Or wherever
import reduxOnDispatch from 'redux-ondispatch';
const store = createStore(reducers, applyMiddleware(
reduxOnDispatch,
// any other middleware
));
That's it! Any action dispatched with a function assigned to a top-level onDispatch
attribute will be executed when the action is dispatched.