/redux-reducer-side-effects

Easy to follow side effect library for redux reducers

Primary LanguageJavaScript

redux-reducer-side-effects

build status npm version license Coverage Status

Easy to follow side effect library for redux reducers

Background

What is a Side Effect?

Anything 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:

  1. Inside of a reducer you may want to have the completion of some operation dispatch another operatop on the store.
  2. 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.

export default function contentReducer(state, action) {
  switch (action.type) {
    case: 'LOGIN': {
      action.addSideEffect((store) => {
        store.dispatch.getContent();
      });
      return state;
    }
    case: 'LOGOUT': {
      action.addSideEffect((store) => {
        store.dispatch.clearContent();
      });
      return state;
    }
    default: {
      return state
    }
  }
}

Installation

# npm
npm install redux-reducer-side-effects --save

# yarn
yarn add redux-reducer-side-effects

Usage

1. Wire up the Middleware

Simply add the middleware when you create your redux store.

import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import addSideEffectMiddleware from 'redux-reducer-side-effects';
import reducers from './reducers';

export default function configureStore() {
  const enhancers = compose(
    applyMiddleware(
      addSideEffectMiddleware()
    )
  );

  return createStore(reducers, {}, enhancers);
}

Optionally, the addSideEffectMiddleware can take in an options object that defines:

  1. timeout: The default timeout in milliseconds for all side effects (defaults to 0 or no timeout)
  applyMiddleware(
    addSideEffectMiddleware({ timeout: 1000 }) // 1 second
  )

2. Add to Reducers

The addSideEffectMiddleware 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.addSideEffect((store) => {
  // Your side effect goes here such as:
  store.dispatch.newAction(action.myNewAction(store.getState().myData));
});

Optionally you can also pass in an object to addSideEffect that defines two properties:

  1. effect: the side effect function as defined above
  2. timeout: a timeout in milliseconds to wrap around the effect function call
action.addSideEffect({
  effect: (store) => {
    // Your side effect goes here such as:
    store.dispatch.newAction(action.myNewAction(store.getState().myData));
  }
  timeout: 1000 // 1 second
});

Example Reducer

export default (state, action) => {
  switch (action.type) {
    case: 'MY_ACTION': {
      const newState = // Perform what ever you need to do here to get your new state

      action.addSideEffect((store) => {
        // Your side effect goes here such as:
        store.dispatch.newAction(action.myNewAction(store.getState().myData));
      });

      // Can add more side effects on action.addSideEffect

      return newState;
    }
    default: {
      return state
    }
  }
}

3. (Optional) Get Information About Side Effects

The addSideEffectMiddleware adds a second new method on the redux reducer action called: sideEffectInfo.
This method returns an object containing information about sideEffects:

  1. count: the current number of side effects that will be executed. this may be useful for testing or other operations
  2. options: the original options passed into addSideEffectMiddleware. you may use this to look at the default timeout or to pass data from the middleware down to sideEffects

License

redux-reducer-side-effects is licensed under the MIT License.