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

xm-redux-actions

v2.0.2

Published

Flux Standard Action utlities for Redux

Downloads

4

Readme

redux-actions

build status

NPM

Flux Standard Action utilities for Redux.

Installation

npm install --save redux-actions

The npm package provides a CommonJS build for use in Node.js, and with bundlers like Webpack and Browserify. It also includes an ES modules build that works well with Rollup and Webpack2's tree-shaking.

If you don’t use npm, you may grab the latest UMD build from unpkg (either a development or a production build). The UMD build exports a global called window.ReduxActions if you add it to your page via a <script> tag. We don’t recommend UMD builds for any serious application, as most of the libraries complementary to Redux are only available on npm.

Usage

createAction(type, payloadCreator = Identity, ?metaCreator)

import { createAction } from 'redux-actions';

Wraps an action creator so that its return value is the payload of a Flux Standard Action.

payloadCreator must be a function, undefined, or null. If payloadCreator is undefined or null, the identity function is used.

Example:

let increment = createAction('INCREMENT', amount => amount);
// same as
increment = createAction('INCREMENT');

expect(increment(42)).to.deep.equal({
  type: 'INCREMENT',
  payload: 42
});

If the payload is an instance of an Error object, redux-actions will automatically set action.error to true.

Example:

const increment = createAction('INCREMENT');

const error = new TypeError('not a number');
expect(increment(error)).to.deep.equal({
  type: 'INCREMENT',
  payload: error,
  error: true
});

createAction also returns its type when used as type in handleAction or handleActions.

Example:

const increment = createAction('INCREMENT');

// As parameter in handleAction:
handleAction(increment, {
  next(state, action) {...},
  throw(state, action) {...}
});

// As object key in handleActions:
const reducer = handleActions({
  [increment]: (state, action) => ({
    counter: state.counter + action.payload
  })
}, { counter: 0 });

NOTE: The more correct name for this function is probably createActionCreator(), but that seems a bit redundant.

Use the identity form to create one-off actions:

createAction('ADD_TODO')('Use Redux');

metaCreator is an optional function that creates metadata for the payload. It receives the same arguments as the payload creator, but its result becomes the meta field of the resulting action. If metaCreator is undefined or not a function, the meta field is omitted.

createActions(?actionMap, ?...identityActions)

import { createActions } from 'redux-actions';

Returns an object mapping action types to action creators. The keys of this object are camel-cased from the keys in actionMap and the string literals of identityActions; the values are the action creators.

actionMap is an optional object and a recursive data structure, with action types as keys, and whose values must be either

  • a function, which is the payload creator for that action
  • an array with payload and meta functions in that order, as in createAction
    • meta is required in this case (otherwise use the function form above)
  • an actionMap

identityActions is an optional list of positional string arguments that are action type strings; these action types will use the identity payload creator.

const { actionOne, actionTwo, actionThree } = createActions({
  // function form; payload creator defined inline
  ACTION_ONE: (key, value) => ({ [key]: value }),

  // array form
  ACTION_TWO: [
    (first) => [first],             // payload
    (first, second) => ({ second }) // meta
  ],

  // trailing action type string form; payload creator is the identity
}, 'ACTION_THREE');

expect(actionOne('key', 1)).to.deep.equal({
  type: 'ACTION_ONE',
  payload: { key: 1 }
});

expect(actionTwo('first', 'second')).to.deep.equal({
  type: 'ACTION_TWO',
  payload: ['first'],
  meta: { second: 'second' }
});

expect(actionThree(3)).to.deep.equal({
  type: 'ACTION_THREE',
  payload: 3,
});

If actionMap has a recursive structure, its leaves are used as payload and meta creators, and the action type for each leaf is the combined path to that leaf:

const actionCreators = createActions({
  APP: {
    COUNTER: {
      INCREMENT: [
        amount => ({ amount }),
        amount => ({ key: 'value', amount })
      ],
      DECREMENT: amount => ({ amount: -amount })
    },
    NOTIFY: [
      (username, message) => ({ message: `${username}: ${message}` }),
      (username, message) => ({ username, message })
    ]
  }
});

expect(actionCreators.app.counter.increment(1)).to.deep.equal({
  type: 'APP/COUNTER/INCREMENT',
  payload: { amount: 1 },
  meta: { key: 'value', amount: 1 }
});
expect(actionCreators.app.counter.decrement(1)).to.deep.equal({
  type: 'APP/COUNTER/DECREMENT',
  payload: { amount: -1 }
});
expect(actionCreators.app.notify('yangmillstheory', 'Hello World')).to.deep.equal({
  type: 'APP/NOTIFY',
  payload: { message: 'yangmillstheory: Hello World' },
  meta: { username: 'yangmillstheory', message: 'Hello World' }
});

When using this form, you can pass an object with key namespace as the last positional argument, instead of the default /.

handleAction(type, reducer | reducerMap = Identity, defaultState)

import { handleAction } from 'redux-actions';

Wraps a reducer so that it only handles Flux Standard Actions of a certain type.

If a reducer function is passed, it is used to handle both normal actions and failed actions. (A failed action is analogous to a rejected promise.) You can use this form if you know a certain type of action will never fail, like the increment example above.

Otherwise, you can specify separate reducers for next() and throw() using the reducerMap form. This API is inspired by the ES6 generator interface.

handleAction('FETCH_DATA', {
  next(state, action) {...},
  throw(state, action) {...}
}, defaultState);

If either next() or throw() are undefined or null, then the identity function is used for that reducer.

If the reducer argument (reducer | reducerMap) is undefined, then the identity function is used.

The third parameter defaultState is required, and is used when undefined is passed to the reducer.

handleActions(reducerMap, defaultState)

import { handleActions } from 'redux-actions';

Creates multiple reducers using handleAction() and combines them into a single reducer that handles multiple actions. Accepts a map where the keys are passed as the first parameter to handleAction() (the action type), and the values are passed as the second parameter (either a reducer or reducer map). The map must not be empty.

The second parameter defaultState is required, and is used when undefined is passed to the reducer.

(Internally, handleActions() works by applying multiple reducers in sequence using reduce-reducers.)

Example:

const reducer = handleActions({
  INCREMENT: (state, action) => ({
    counter: state.counter + action.payload
  }),

  DECREMENT: (state, action) => ({
    counter: state.counter - action.payload
  })
}, { counter: 0 });

combineActions(...types)

Combine any number of action types or action creators. types is a list of positional arguments which can be action type strings, symbols, or action creators.

This allows you to reduce multiple distinct actions with the same reducer.

const { increment, decrement } = createActions({
  INCREMENT: amount => ({ amount }),
  DECREMENT: amount => ({ amount: -amount }),
})

const reducer = handleAction(combineActions(increment, decrement), {
  next: (state, { payload: { amount } }) => ({ ...state, counter: state.counter + amount }),
  throw: state => ({ ...state, counter: 0 }),
}, { counter: 10 })

expect(reducer(undefined, increment(1)).to.deep.equal({ counter: 11 })
expect(reducer(undefined, decrement(1)).to.deep.equal({ counter: 9 })
expect(reducer(undefined, increment(new Error)).to.deep.equal({ counter: 0 })
expect(reducer(undefined, decrement(new Error)).to.deep.equal({ counter: 0 })

Here's an example using handleActions:

const { increment, decrement } = createActions({
  INCREMENT: amount => ({ amount }),
  DECREMENT: amount => ({ amount: -amount })
});

const reducer = handleActions({
  [combineActions(increment, decrement)](state, { payload: { amount } }) {
    return { ...state, counter: state.counter + amount };
  }
}, { counter: 10 });

expect(reducer({ counter: 5 }, increment(5))).to.deep.equal({ counter: 10 });
expect(reducer({ counter: 5 }, decrement(5))).to.deep.equal({ counter: 0 });
expect(reducer({ counter: 5 }, { type: 'NOT_TYPE', payload: 1000 })).to.equal({ counter: 5 });
expect(reducer(undefined, increment(5))).to.deep.equal({ counter: 15 });

Usage with middleware

redux-actions is handy all by itself, however, its real power comes when you combine it with middleware.

The identity form of createAction is a great way to create a single action creator that handles multiple payload types. For example, using redux-promise and redux-rx:

const addTodo = createAction('ADD_TODO');

// A single reducer...
handleAction('ADD_TODO', (state = { todos: [] }, action) => ({
  ...state,
  todos: [...state.todos, action.payload]
}));

// ...that works with all of these forms:
// (Don't forget to use `bindActionCreators()` or equivalent.
// I've left that bit out)
addTodo('Use Redux')
addTodo(Promise.resolve('Weep with joy'));
addTodo(Observable.of(
  'Learn about middleware',
  'Learn about higher-order stores'
)).subscribe();

See also

Use redux-actions in combination with FSA-compliant libraries.