Do something async when Redux action happens. Yet another (tiny, ~185 bytes) Redux async middleware.
npm install --save redux-on-action
First you have to apply the middleware:
import { createStore, applyMiddleware } from 'redux';
import createOnActionMiddleware from 'redux-on-action';
import rootReducer from './reducers/index';
const { middleware, onAction } = createOnActionMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(middleware),
);
Then you can setup action listener:
onAction('IMPORT_START_REQUEST', async (action, dispatch, getState) => {
dispatch({ type: 'IMPORT_STARTED' });
await importDirectory(
action.payload.directoryPath,
importedFileCount => dispatch({ type: 'IMPORT_PROGRESS', payload: importedFileCount }),
);
dispatch({ type: 'IMPORT_FINISHED' });
});
Returns object with fields:
middleware
- Function, Redux middleware.onAction
- Function, see onAction.
Registers action listener. When specified action is dispatched - provided function will be called.
action
- String, type of Redux action.callback
- onActionCallback, function that will be called when action is dispatched.
Function specified as onAction callback.
action
- Object, dispatched Redux action.dispatch
- Function, Redux dispatch function.getState
- Function, Redux getState function.
You can setup many listeners for single action type. Every registered callback will be called in order in which they were registered.
onAction('MY_ACTION', () => console.log('first!'));
onAction('MY_ACTION', () => console.log('second!'));
dispatch({ type: 'MY_ACTION' });
// first!
// second!
This project is licensed under the MIT license.