redux-reducer-side-effects
Easy to follow side effect library for redux reducers
Background
Side Effect?
What is aAnything that modifies some state outside its scope or has an observable interaction with its calling functions or the outside world beyond returning a value.
In redux, this means if your reducer does anything beyond just returning the new state for that reducer, its a side effect and needs to be handled as such.
However, often reducers will need to perform some kind of side effect. In these situations, you want to perform these side effects "outside" of the reducer. For instance:
- Inside of a reducer you may want to have the completion of some operation dispatch another operatop on the store.
- Reducers should not know about one another direct, but may listen for well known actions between them.
What does this library do for me?
There are a few different side effect libraries out there, but many do more than you need or are hard to follow. Primary goal of this library is to introduce safe side effects in a powerful way, but be simple to read, understand, and implement.
For instance, say you have two reducers, one for login (loginReducer) and the other for content (contentReducer). When a user logs in, you want to retrieve content, and when the user logs out, you want to remove the content.
{ }
Installation
# npmnpm install redux-reducer-side-effects --save# yarnyarn add redux-reducer-side-effects --dev
Usage
Middleware
1. Wire up theSimply add the middleware when you create your redux store.
;;;{const enhancers =;return ;}
Optionally, the addSideEffectMiddlware
can take in an options object that defines:
timeout
: The default timeout in milliseconds for all side effects (defaults to 0 or no timeout)
2. Add to Reducers
The addSideEffectMiddlware
adds a new method on the redux reducer action
called: addSideEffect
.
This method takes in a function that is passed the entire redux store
. This allows the side effect to getState()
or dispatch
new actions onto the store.
action;
Optionally you can also pass in an object to addSideEffect
that defines two properties:
effect
: the side effect function as defined abovetimeout
: a timeout in milliseconds to wrap around theeffect
function call
action;
Example Reducer
{}
3. (Optional) Get Information About Side Effects
The addSideEffectMiddlware
adds a second new method on the redux reducer action
called: sideEffectInfo
.
This method returns an object containing information about sideEffects:
count
: the current number of side effects that will be executed. this may be useful for testing or other operationsoptions
: the original options passed intoaddSideEffectMiddlware
. you may use this to look at the defaulttimeout
or to pass data from the middleware down to sideEffects
License
redux-reducer-side-effects
is licensed under the MIT License.