Redux-Jian
Redux-Jian is a library aiming to simplify how to use Redux. Jian (chinese: 簡) means 'simple' or 'simplify'.
- Declare mutators (action creators) in one singleton, and you can get a mutator by its name anywhere. It's highly decoupling and easy to use.
- Bind mutators to Redux store once, and you'll no longer need to use
mapDispatchToProps
in theconnect()
.
How to use
Make an action
makeAction()
is a Redux action synthesizer. It simply wrap data in the key payload
. If the data is an Error
type, the value of isError
will be true
.
const updateUsernameAction = makeAction(UPDATE_USERNAME, { username: name })
// same as
const updateUsernameAction = {
type: UPDATE_USERNAME,
payload: {
username: name
},
isError: false
}
Mutators (action creators)
Mutators are just action creators in Redux. A mutator usually is also a thunk which allow you decide when and what action you want to dispatch (you need to use the middleware 'redux-thunk' to achieve this). Futhermore, you may want to introduce some side-effects before dispatching the action to reducers (pure functions), and the mutators are the places where you can handle them.
Register a mutator:
// user.redux.js
import { createMutator, action } from 'redux-jian';
const UPDATE_USERNAME = 'UPDATE_USERNAME';
// simple mutator
createMutator(UPDATE_USERNAME, (name) => {
if (name.length > 0) {
return makeAction(UPDATE_USERNAME, { username: name });
}
return makeAction(INPUT_INVALID_USERNAME);
})
// thunk mutator
Get a mutator by a name:
// Signup.js (a React component)
import { getMutator } from 'redux-jian';
const updateUsernameMutator = getMutator('UPDATE_USERNAME');
const updateUsernameAction = updateUsernameMutator('John');
// or use currying
const updateUsernameAction = getMutator('UPDATE_USERNAME')('John');
// dispatch the action to Redux store
store.dispatch(updateUsernameAction);
- You can get the mutator by its name (a string key) without importing the file where you implement it.
- Redux-Jian allow to register each name only once. If registering a duplicated mutator name, it will throw an error.
Bound mutators
Redux-Jian provides a way to bind mutators to a store:
// App.js
import { bindMutatorsToDispatch } from 'redux-jian';
const store = createStore(...);
bindMutatorsToDispatch(store.dispatch);
Now you can use bound mutators directly:
// Signup.js (a React component)
import { boundMutators } from 'redux-jian'
boundMutators('UPDATE_USERNAME')('John');
Why using bound mutators? In the standard Redux way, you need to use mapDispatcherToProps()
and connect()
to bind mutators to a dispatcher. This is redundant because there is only a store, and only a dispatcher, for the app states. All actions will only be sent to this store. This means that we could bind all mutators to the store only once and use them anywhere.
You can choose to use getMutator()
and dispatch it manually or just use boundMutator()
to dispatch actions (or invoke the thunk) directly.
Installation
npm install --save redux-jian