rehash
A set of utilities to generate an initial state, a reducer, and an action creator tree for use with redux.
Usage
npm install rehash
;; const storeDef = items: 'foo' Object nested: items: 'bar' Object ; const state reducer getDispatchTree = ;const store = ;const dispatchTree = ; store; console; // ['bar', 'baz'] dispatchTreenested; console; // ['bar', 'baz', 'qux']
Concepts
At its simplest, rehash is a utility to create a redux reducer from a rehash store definition that looks like this:
const storeDef = items: 'foo' Object nested: items: 'bar' Object ;
Note: A store definition mixes both the initial state and the state mutation functions (or xforms) into a single object so you can easily see the shape of the state that each xform is operating on.
Reducer
Rehash takes this store definition and returns an initial state
, and a redux reducer
.
const state reducer = ;
These can be used like any other handwritten reducer in redux. The handwritten equivalent to the above would look like this:
const reducer = { };
Store/dispatch
Use state
and reducer
with redux:
const store = ;
You can now dispatch actions with two properties, type
, which is generated from the "path" to the xform in the store definition, and payload
, which is given to the xform as the second argument.
store;
DispatchTree
Rehash also returns a function getDispatchTree
which, after store creation, you can call with the dispatch
function to get a dispatchTree
.
const state reducer getDispatchTree = ;const store = ;const dispatchTree = ;
This is a simple object that mirrors the shape of the xform tree to provide a little bit of sugar over calling store.dispatch
directly. The following are equivalent:
store; dispatchTreenested;
Thunks
Because rehash returns a simple reducer, integration with other redux libraries is seamless.
;;; const storeDef = ...; const state reducer getDispatchTree = ;const store = createStorereducer state;const dispatchTree = ; const thunkActionCreator = { ; // OR ;});
You can also use some utilities that rehash provides to include thunk action creators into your store definition:
;; const storeDef = items: 'foo' Object nested: items: 'bar' Object // wrap the thunk xform so rehash knows what to do with it thunkActionCreator: async { ; }; const opts = // a rehash-provided config function to interpret thunks in your store def createActionCreator: thunkCreateActionCreator // tells rehash to ignore thunk xforms when creating the reducer reducerTreeFilterFn: isThunk; const state reducer getDispatchTree = ;const store = createStorereducer state;const dispatchTree = ; // thunks can now be dispatched directly from the dispatchTreedispatchTree;
To see a full example using redux.combineReducers
, redux-thunk
, and redux-router
with rehash
, check out src/example.jsx
.
Advanced
@todo: document custom createActionCreator, reducerTreeFilterFn, and actionHandler functions.