Redux Utils
Experimenting with some Redux sugar
by soulwire
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.5.2/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/2.1.0/redux-thunk.min.js"></script>
Babel + JSX
// ——————————————————————————————————————————————————
// Dependencies
// ——————————————————————————————————————————————————
const { createStore, combineReducers, applyMiddleware } = Redux;
const thunk = ReduxThunk.default;
// ——————————————————————————————————————————————————
// Utils
// ——————————————————————————————————————————————————
const makeAwesome = (initialState, actions = {}, namespace) => {
const creators = {};
const handlers = {};
for (let name in actions) {
const type = namespace ? `${namespace}:${name}` : name;
creators[name] = (...data) => ({ type, data });
handlers[type] = actions[name];
}
const reducer = (state = initialState, action) => {
const handler = handlers[action.type];
if (handler) {
return handler.apply(handler, [state, ...action.data]);
}
return state;
};
return { ...creators, reducer };
};
// ——————————————————————————————————————————————————
// Awesome
// ——————————————————————————————————————————————————
const awesome = (() => {
const initialState = { value: 0 };
const incrementValue = (state, value) => ({ ...state, value });
const sumValues = (state, a, b) => ({ ...state, value: a + b });
return makeAwesome(initialState, {
incrementValue,
sumValues
}, 'awesome');
})();
// ——————————————————————————————————————————————————
// Regular
// ——————————————————————————————————————————————————
const regular = (() => {
const UPDATE_VALUE = 'UPDATE_VALUE';
const SUM_VALUES = 'SUM_VALUES';
const incrementValue = (value) => ({
type: UPDATE_VALUE,
data: value
});
const sumValues = (a, b) => ({
type: SUM_VALUES,
data: { a, b }
});
const multiplyAsync = (factor) => (dispatch, getState) => {
const { regular } = getState();
setTimeout(() => {
dispatch({
type: UPDATE_VALUE,
data: regular.value * factor
});
}, 200);
};
const initialState = { value: 0 };
const reducer =...