Action handler middleware for Redux.
npm install --save redux-reactions
I felt I needed a way to wait for an action to be dispatched in Redux, and respond to it in some way other than manipulating the store.
Like redux-saga, but much lighter.
Lots of people have had a take on this, here are some middlewares I found that may suit you better:
- redux-listeners
- redux-observable
- redux-hook-middleware
- redux-listener
- redux-fries
- redux-action-listeners
First, register the middleware:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { createReactionsMiddleware } from 'redux-reactions';
const todoApp = combineReducers(reducers);
const store = createStore(
todoApp,
applyMiddleware(createReactionsMiddleware())
);
Next up, just like your actions go into a seperate file; for example actions/index.js
, your reactions should also be seperated:
import * as constants from "./constants";
export function handleNewTodo(addReaction) {
addReaction(constants.ADD_TODO, (dispatch, getState, action) => {
/*
* Do something, but don't dispatch ADD_TODO again or
* you will enter a loop.
*
* You can perform asynchronous work here.
*/
});
}
And now in your container, register your reactions:
import { connect } from 'react-redux';
import { registerReactions } from 'redux-reactions';
import TodoList from 'components/TodoList';
import * as reactions from './reactions';
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({});
registerReactions(reactions);
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoList);
Many thanks to Ben Anderson for giving up the redux-reactions npm package name.