A small library to help build Redux reducers and their associated actions.
Actionize helps you build Redux reducers without having to write large switch statements to handle actions or create action factories to call them. Actionize maintains a set of reducer names and ensures they are unique; this ensures all actions have unique names for dispatching.
import Actionize from 'actionize';
const actionize = new Actionize();
// Create a reducer:
const todoList = actionize.define('todos.list', build => build.reducer([], {
// An action:
// Takes the current state and arguments, and returns the new state.
add(state, { text }) {
return [
...state,
{ id: state.length + 1, text: text, done: false }
];
},
complete(state, { id }) {
return state.map(value => value.id === id
? Object.assign({}, value, { done: true })
: value
);
}
}));
The Actionize API is handled through two classes, Actionize
and ActionizeBuild
.
The .set
and .define
function on the Actionize
class are given a builder which receives an instance of ActonizeBuild
.
new Actionize(options)
Create a new instance of actionize. The given options are:
Option | |
---|---|
context |
A function that returns the this context for action handlers in the format function(action, reducer) |
Immutable |
A reference to the Immutable JS library instance. This is used for .combineImmutable and .nestImmutable |
.set(string name, function(ActionizeBuild build) builder)
Set a reducer by name. The builder
function should return the reducer. The name
given must be unique per instance of Actionize
.
This function is lazy and will not call builder
until .get
is called for the same name.
actionize.set('foo', build => build.reducer({}, {
doSomething(state, { arg }) {
return { ...state, arg };
}
});
.define(string name, function(ActionizeBuild build) builder)
Same as .set
, but not lazy. Returns the reducer from builder
immediately.
const fooReducer = actionize.define('foo', build => build.reducer(...));
.get(string name)
Get a reducer by name. This will invoke the builder
prebiously given to .set
for the same name.
If .get
was called previously for the same name, the same instance will be returned.
actionize.set('foo', build => build.reducer(...));
// ...
const fooReducer = actionize.get('foo');
.dispatcher(function reducer, function reduxStoreDispatch)
Create a dispatcher object from the given reducer and Redux dispatch store. This will allow calling functions directly on the dispatcher without needing a reference to the redux store.
actionize.dispatcher(actions, reduxStoreDispatch)
Argument | |
---|---|
reducer |
A reducer. |
reduxStoreDispatch |
The Redux store.dispatch function. |
const todoListActions = actionize.dispatcher(todoList, store.dispatch);
todoListActions.edit({
id: 123,
todo: { text: 'foo' }
});