I would recommend @acdlite's redux-actions over the methods suggested in this Gist.
The methods below can break hot-reloading and don't support Promise-based actions.
Even though 'redux-actions' still uses constants, I've come to terms with the fact that constants can be good, especially in bigger projects. You can reduce boilerplate in different places, as described in the redux docs here: http://gaearon.github.io/redux/docs/recipes/ReducingBoilerplate.html
Redux is super lightweight...so it may be useful to add some helper utils on top of it to reduce some boilerplate. The goal of Redux is to keep these things in user-land, and so most likely these helpers (or anything like them) wouldn't make it into core.
It's important to note that this is just ONE (and not particularly thoroughly tested) way to accomplish the goal of reducing boilerplate in Redux. It borrows some ideas from Flummox and the way it generates action creator constants.
This will evolve, I'm sure, as time goes on and as Redux's API changes.
Some helper functions to reduce some boilerplate in Redux:
import _ from 'lodash';
import uniqueId from 'uniqueid';
// Create actions that don't need constants :)
export const createActions = (actionObj) => {
const baseId = uniqueId();
return _.zipObject(_.map(actionObj, (actionCreator, key) => {
const actionId = `${baseId}-${key}`;
const method = (...args) => {
const result = actionCreator(...args);
return {
type: actionId,
...(result || {})
};
};
method._id = actionId;
return [key, method];
}));
};
// Get action ids from actions created with `createActions`
export const getActionIds = (actionCreators) => {
return _.mapValues(actionCreators, (value, key) => {
return value._id;
});
};
// Replace switch statements in stores (taken from the Redux README)
export const createStore = (initialState, handlers) => {
return (state = initialState, action) =>
handlers[action.type] ?
handlers[action.type](state, action) :
state;
};
They can be used like this:
import {createActions} from 'lib/utils/redux';
export const SocialPostActions = createActions({
loadPosts(posts) {
return { posts };
}
});
import {default as Immutable, Map, List} from 'immutable';
import {createStore, getActionIds} from 'lib/utils/redux';
import {SocialPostActions} from 'lib/actions';
const initialState = Map({
isLoaded: false,
posts: List()
});
const actions = getActionIds(SocialPostActions);
export const posts = createStore(initialState, {
[actions.loadPosts]: (state, action) => {
return state.withMutations(s =>
s.set('isLoaded', true).set('posts', Immutable.fromJS(action.posts))
);
}
});
Doesn't seem to work for async actions that return a function.