duxions
v0.0.1
Published
Actions and Reducers with less boilerplate, cleaner readability, and simple testing
Downloads
1
Maintainers
Readme
Duxions: A clear way to write action/reducer pairs.
The Standard Redux Example
After working with Redux for a while, our team at Vevo come to a common conclusion that there is a lot of boilerplate required for actions and reducers. We love avoiding setState()
and instead using actions/reducers, but it can become quite tedious. Take this widget creator for example:
// ToDoActions.js
// TYPES
export const CREATE = 'my-app/toDos/CREATE';
export const UPDATE = 'my-app/toDos/UPDATE';
export const SET_ACTIVE_INDEX = 'my-app/toDos/SET_ACTIVE_INDEX';
// ACTION
export function createToDo(todo) {
return { type: CREATE, todo };
}
export function updateToDo(todo) {
return { type: UPDATE, todo };
}
export function setActiveIndex(activeIndex) {
return { type: SET_ACTIVE_INDEX, activeIndex };
}
// ToDoReducer.js
import { CREATE, UPDATE, SET_ACTIVE_INDEX } from "./actions";
// REDUCER
export default function reducer(state = {toDos: []}, action = {}) {
switch (action.type) {
case CREATE:
state.toDos = state.toDos.push(action.todo);
break;
case UPDATE:
state.toDos = state.toDos.map(
todo => (
todo.id === action.todo.id ? action.todo : todo
)
);
break;
case SET_ACTIVE_INDEX:
state.activeIndex = action.activeIndex;
break;
default: return state;
}
return state;
}
Whats difficult with this traditional approach?
- Its a lot of boilerplate to write.
- Switching between all of these files requires more cognitive load when developing.
- PRs are difficult when all of your code is separated like this. The related code can appear in very different places.
So we thought how could we improve this?
- What if we don't have to manually write types anymore?
- What if we put actions and reducers together so that they are more readable?
Our approach
For the basic example, we replicate the code from above in a much shorter syntax
// ToDoDuxion.js
import createActionReducer from 'duxions';
const NAMESPACE = 'app/todos';
const initialState = {
toDos: [],
activeToDoIndex
};
const actionReducers = {
createToDo: {
action: toDo => {payload: toDo}, // NO TYPE NEEDED! They get generated automatically
reducer: state => {
state.toDos = state.toDos.push(action.payload);
return state;
}
},
updateToDo: {
action: toDo => { payload: toDo},
reducer: state => {
state.toDos = state.toDos.map(
todo => (
todo.id === action.todo.id ? action.todo : todo
)
);
return state;
}
},
// You can also just write functions that return an object that is merged into your store.
setActiveToDoIndex: index => ({activeToDoIndex: index})
}
const actionsReducerPair = createActionReducer(NAMESPACE, initialState, actionReducers);
export const { actions } = actionsReducerPair;
export const { reducer } = actionsReducerPair;
What is it doing?
Its actually just doing Redux. It looks at the Lets walk through this:
- Because our actions and reducers are named keys in an object, we can auto generate our types for actions and reducers from that key. For example createToDo would have a type that looks like this:
app/todos/createToDo
. - The reducer is automatically bound to that type. This is actually a small performance improvement over traditional switch statements, because it uses object indexing rather than a switch statement to handle the reducer.
- Because the reducer and actions are exported, the store and its actions can be referenced using standard redux just like any other set of action/reducer pairs.
- What if you want to have multiple reducers respond to the same action type?
- This can be an anti-pattern as it makes it harder to track how changes in your codebase are affecting each other. One of the goals of this setup is to keep actions and their reducers co-located. There is a way to override this behavior though, by passing your own "type" field to the object returned by your action.
Normal action/reducer pairs:
const actionReducers = {
setThing: {
action: (thing) => {payload: thing}
reducer: (state) => {state.thing = payload.thing; return state;}
}
}
Shorthand for pure functional actions:
This shorthand should feel just as easy as using setState({mergeMe:true})
in a component. It just merges the object returned from the function into your store.
const actionReducers = {
setThing: (thing) => ({thing}) // the returned object is merged into the store.
}
This function will merge only if it receives an object.
Asynchronous actions (thunks) shorthand
If you use the shorthand and return a function, then it will call that function with (actions, dispatch, getState);
const actionReducers = {
// Loading State
setLoading: (isLoading) => ({isLoading}),
loadFail: (error) => ({ isLoading: false, error }),
// Thing actions
setThing: (thing) => {things: {[thing.id]: thing}}
getThing: (thingId) => async (actions, dispatch, getState) => {
try {
dispatch(actions.setLoading(true));
const thing = await myAPI.getThing(thingID);
dispatch(actions.setThing(thing));
dispatch(actions.setLoading(false));
} catch (err) {
dispatch(actions.loadThingFail(err));
}
},
};
Now take a second to stop and think about that previous example. How many lines of boilerplate would be needed with traditional redux? Three of our action/type/reducers were reduced to a single line of code, and with traditional redux would have each been at least 7 lines of code.