npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

redux-action-reducer

v1.3.0

Published

Remove redux reducer boilerplate

Downloads

4,062

Readme

redux-action-reducer

Remove redux reducer boilerplate

Your actions need to comply with FSA (Flux Standard Action).

npm i --save-dev redux-action-reducer

createReducer(...actionHandlers)(defaultValue)

actionHandler: String | Array

An actionHandler is an action type (String) or a list of action types (Array) with an optional action reducer at the end. By default, an action reducer returns its payload: (state, payload, error) => payload.

// [ 'ACTION1', (state, payload) => payload ]
'ACTION'

// [ 'ACTION1', 'ACTION2', (state, payload) => payload ]
[ 'ACTION1', 'ACTION2' ]

[ 'ACTION1', (state, payload) => ({ ...state, [payload.id]: payload }) ]

whenError and whenSuccess

whenError and whenSuccess are shorthand methods to avoid having to differentiate between error and success in action reducers. whenError will only apply to actions with error: true, the current state will be returned if an action is not an error. successReducer works the other way round.

whenError and whenSuccess both accept a reducer function (state, payload) => /*...*/.

import createReducer, { whenSuccess } from 'redux-action-reducer';

const list = createReducer(
    [ 'ACTION', whenSuccess((state, payload) => state.concat(payload))]
);

// Instead of
const list = createReducer(
    [ 'ACTION', (state, payload, error) => error ? state : state.concat(payload)) ]
);

If a reducer is not supplied, payload will be returned.

extendReducer(reducer)(...actionHandlers)(defaultValue)

Re-use an existing reducer and extend it with extra handlers using this pattern, for example:

const reducer = [ 'ACTION1', (state, payload) => ({ ...state, [payload.id]: payload }) ]
const reducer2 = extendReducer( reducer, 'ACTION2', [ 'ACTION3', () => ({}) ])

This comes in handy when a common pattern for a reducer can be re-used throughout the application, but sometimes requires extra cases handling.

Reducer Factories

What are reducer factories?

In an application it is common for patterns to become reused many times over, in these cases some form of abstraction is useful. This library can be used to define a reducer factory that can be re-used throughout the code-base, here is an example.

// queryReducerFactory.js
export default ({ setAll, setField, resetAll }) => createReducer(
  setAll,
  [ ...setField, (state, payload) => ({ ...state, [payload.id]: payload.value }) ],
  [ ...resetAll, () => ({}) ]
)({})

This factory will create a reducer that can be combined wherever is useful in the state tree (using redux combineReducers), and is generated by passing in an object with 3 arrays of actions to perform the functions, setAll, setField and resetAll.

This factory could be implemented as follows:

import queryReducer from './queryReducerFactory'

const reducer = queryReducer({
  setAll: [ 'ACTION1', 'ACTION2' ],
  setField: [ 'ACTION3' ],
  resetAll: [ 'ACTION4', 'ACTION5' ]
})

This gives full flexibility when defining which actions will be allowed to trigger the reducer behaviour. Extra cases can be handled in specific instantiations by using the extendReducer pattern (Above)

Examples

Full example

We can search a list of items, add or remove them from a list and empty that list.

import { combineReducers } from 'redux';
import createReducer from 'redux-action-reducer';
import { SEARCH, CLEAR_SEARCH, ADD_ITEM, REMOVE_ITEM, EMPTY } from './actionTypes';

const search = createReducer(
    SEARCH,
    [ CLEAR_SEARCH, () => '' ]
)('');

const selectedItems = createReducer(
    [ ADD_ITEM, (state, payload) => state.concat(payload) ],
    [ REMOVE_ITEM, (state, payload) => state.filter(item => item !== payload) ],
    [ EMPTY, () => [] ]
)('');

export default combineReducers({
    search,
    selectedItems
});

Single action reducer, primitive value

function search(state = 'info', action) {
    switch (action.type) {
        case SELECT_TAB:
            return action.payload;

        default:
            return state;
    }
}

becomes:

import createReducer from 'redux-action-reducer';

const search = createReducer(SELECT_TAB)('info');

Multiple action reducer, primitive value

function search(state = '', action) {
    switch (action.type) {
        case SEARCH:
            return action.payload;

        case CLEAR_SEARCH:
            return '';

        default:
            return state;
    }
}

becomes:

const search = createReducer(
    SEARCH,
    [ CLEAR_SEARCH, () => '' ]
)('');

Multiple-action reducer, array

function selectedItems(state = [], action) {
    switch (action.type) {
        case ADD_ITEM:
            return state.concat(action.payload);

        case REMOVE_ITEM:
            return state.filter(item => item !== payload);

        case EMPTY:
            return [];

        default:
            return state;
    }
}

becomes:

const selectedItems = createReducer(
    [ ADD_ITEM, (state, payload) => state.concat(payload) ],
    [ REMOVE_ITEM, (state, payload) => state.filter(item => item !== payload) ],
    [ EMPTY, () => [] ]
)('');