Dispatch async action listener at any time and do side effect for Redux.
$ npm install --save redux-listener
import { createStore, applyMiddleware } from 'redux';
import { createListenerMiddleware, on, attach } from 'redux-listener';
import rootReducer from './reducers';
const reduxListenerMiddleware = createReduxListenerMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(createListenerMiddleware)
);
async function someFunction() {
// 'on' is a plain action creator to help to add the listenr
store.dispatch(on('ASYNC_MESSAGE', (action, { dispatch }) => {
return new Promise(resolve => {
setTimeout(() => {
console.info('');
resolve();
}, 1000);
});
}));
store.dispatch({
type: 'INCREMENT_ASYNC',
});
const result = await attach(store.dispatch({
}))
}
The basic concept of redux-listener is
Do dispatch(async listener) for redux action at any time.
To archive this, there are serveral advanced concepts that are designed.
1. Action listener is only for side effect, so the original redux data flow shouldn't be interrupted.
// Chart
Eazy to do code splitting. Just dispatch and add required async action listeners before business logic.
Easy to make test. You can mock and override any exist listener to test.
So there are only on(type, listener) and off(type, listener), and no addListener and removeListener in order to avoid misunderstanding.
However multiple listeners can be composed as one listener for one action type.
There is an example.
import { query, on, attach } from 'redux-listener';
async function someFunction() {
const existListener = await attach(dispatch(query('SOME_ACTION_TYPE')));
dispatch(on('SOME_ACTION_TYPE', async (action, ...args) => {
// do something
const originalResult = await existListener(action, ...args);
// do something
return originalResult; // Or something else
}));
}
For chaining multiple async action.
async function someFunction() {
await attach(dispatch({
type: "ASYNC_FETCH_SCHOOL_REQUEST",
payload: {
schoolId: 3
}
}));
const school = selectSchool(getState(), 3);
const classroomIds = school.classrooms;
const classroomPromises = classroomIds.map((id) => {
return attach(dispatch({
type: "ASYNC_FETCH_CLASSROOM_",
payload: {
classroomId: id
}
}));
});
await Promise.all(classroomPromises);
// ...
}
But take care of dispatching actions inside the async listener, it may cause infinite loop!!
For npm
npm install --save redux-listener
For yarn
yarn add redux-listener
Create a new listener middleware with extra argument.
const store = createStore(
reducer,
applyMiddlware(createListenerMiddleware({ api, whatever })),
);
store.dispatch(on('TYPE_OF_ACTION', async (action, dispatch, getState, { api, whatever }) => {
}));
Adds an action listener for type. The value returned by listener can be accessed by attach()
function.
store.dispatch(on('TYPE_OF_ACTION', async (action, dispatch, getState, extraArgument) => {
// ...
}));
type
( String ): Action type.listener(action, dispatch, getState, extraArgument): Promise or any
( Function ): Listener for specified action type. Thedispatched action
,dispatch
,getState
,extraArgument
will be passed. Promise is recommended returned type, since the result can be accessed byattach()
.
Removes an action listen for type.
store.dispatch(off('TYPE_OF_ACTION'));
An action creator that is used to remove the listener for type.
An action creator that is used to query the registered listener for type. Use attach(result)
to access the returned listener.
async function example() {
const result = store.dispatch(query('TYPE_OF_ACTION'));
const listener = await attach(result);
}
You can use this function to delegate the exist listener.
Attachs the listener of dispatched action and gets the result.
async function example() {
store.dispatch(on('ACTION_TYPE_A', async (action, dispatch, getState, extraArgument) => {
const { msg } = action.payload;
return msg;
}));
const result = store.dispatch({
type: 'ACTION_TYPE_A',
payload: {
msg: 'Hello'
}
});
const listenerResult = await attach(result);
console.info(listenerResult); // "Hello"
}
MIT