Skip to content

jkusachi/redux-actions

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

88 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

redux-actions

build status npm version

Flux Standard Action utilities for Redux.

npm install --save redux-actions
import { createAction, handleAction, handleActions } from 'redux-actions';

(NEW) createAPIAction(type, method, endpoint, payloadCreator = Identity, ?metaCreator)

Wraps an action creator so that its return value is the payload of a Flux Standard Action, and also creates multiple actions types that can be handled via middleware (Request, Success, and Failure Types).

The parameters you pass to your action are verb dependant

Also adds meta data, such as the method and endpoint to be used where you see fit.

If no payload creator is passed, or if it's not a function, the identity function is used.

Example:

let createContact = createAPIAction('CREATE_CONTACT', 'POST', '/contacts' );

expect(createContact( {name: "James Kusachi"} )).to.deep.equal({
  type: 'CREATE_CONTACT',
  payload: {name: "James Kusachi"},
  meta: {
  	api: true,
  	method: 'POST',
  	endpoint: '/contacts',
  	types: [
  		'CREATE_CONTACT_REQUEST',
  		'CREATE_CONTACT_SUCCESS',
  		'CREATE_CONTACT_FAILURE',
  	]
  }
});

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

The following are Verb Based Examples so you can see how to use your actions

GET
let getItems = createAPIAction('ITEMS', 'GET', '/items' );
getItems()

there is no need to pass a payload to your action, as its a GET request

Auto Generated Action Types

  • ITEMS_DELETE_REQUEST
  • ITEMS_DELETE_SUCCESS
  • ITEMS_DELETE_FAILURE
GET (single)
let getSingleItem = createAPIAction('SINGLE_ITEM', 'GET', '/items' );
getSingleItem(15)

Here, we pass 15 as a parameter to the action, representing a case where we want only 1 item. It's also important to note that we used a separate key, SINGLE_ITEM, to differentiate between a single and All request.

Auto Generated Action Types

  • SINGLE_ITEM_DELETE_REQUEST
  • SINGLE_ITEM_DELETE_SUCCESS
  • SINGLE_ITEM_DELETE_FAILURE
POST
let createItem = createAPIAction('ITEMS', 'POST', '/items' );
createItem({name: "James Kusachi");

In a case where you POST new data, you dont need to specify an id, but you do need to pass data. Any data passed as the first parameter will be treated as the payload to be sent across.

Auto Generated Action Types

  • ITEMS_POST_REQUEST
  • ITEMS_POST_SUCCESS
  • ITEMS_POST_FAILURE
PUT
let updateItem = createAPIAction('ITEMS', 'PUT', '/items' );
updateItem(15, {name: "Ronald McDonald");

In the event of an UPDATE, you generally need to specify 2 pieces

  • id of item you are updating
  • the data you want to update with

In this case, we are updating primary item 15 with a new object

Auto Generated Action Types

  • ITEMS_PUT_REQUEST
  • ITEMS_PUT_SUCCESS
  • ITEMS_PUT_FAILURE
DELETE
let deleteItem = createAPIAction('ITEMS', 'DELETE', '/items' );
updateItem(15);

In the case of DELETE, you just need to specify the primary id of tha which you want to delete. No need to pass in any payload data, as that would get dropped anyways because of DELETE

Auto Generated Action Types

  • ITEMS_DELETE_REQUEST
  • ITEMS_DELETE_SUCCESS
  • ITEMS_DELETE_FAILURE

createAction(type, payloadCreator = Identity, ?metaCreator)

Wraps an action creator so that its return value is the payload of a Flux Standard Action. If no payload creator is passed, or if it's not a function, 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
});

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.

handleAction(type, reducer | reducerMap)

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

If a single reducer 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(). This API is inspired by the ES6 generator interface.

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

handleActions(reducerMap, ?defaultState)

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 optional second parameter specifies a default or initial state, which 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 });

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.

About

Flux Standard Action utilities for Redux.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 98.6%
  • Makefile 1.4%