A functional redux util to replace the switch case statement.
Get the pattern below as alternative to switch case statement.
The reducerMatching
is an useful function and can replace the switch statement in the project, assuming a functional posture in the code.
npm install --save reducer-matching
var reducerMatch: [string, function] = [types.INC_COUNT, (state, action) => 'do something...'];
In case of no matches, the reducer matching will return the state without changes.
import reducerMatching from 'reducer-matching';
const initialState = {};
const reducer = (state = initialState, action) => reducerMatching(
[ types.INC_COUNT, incrementCounter ],
[ types.DEC_COUNT, decrementCounter ],
[ types.FETCH_USERS, fetchUsers ],
[ types.FETCH_USERS_SUCCESS, fetchUsersSuccess ],
[ types.FETCH_USERS_FAILURE, fetchUsersFailure ]
)(state, action);
// ... some reducers
function fetchUsersSuccess(state, action) {
return {
...state,
isFetchingUsers: false,
users: action.payload,
};
}
// ... other reducers
export default reducer;
The tests was make in Jest.
npm run test
Any PR is welcome! :D
- Ramda - A practical functional library for JavaScript programmers.
- Before:
const reducer = (state = appInitialState, action) => {
switch (action.type) {
case types.INC_COUNT:
return { ...state, count: state.count + 1 };
case types.DEC_COUNT:
return { ...state, count: state.count - 1 };
case types.INC_TEN_COUNT:
return { ...state, count: state.count + 10};
case types.DEC_TEN_COUNT:
return { ...state, count: state.count - 10 };
case types.FETCH_USERS:
return { ...state, isFetchingUsers: true };
case types.FETCH_USERS_SUCCESS:
return {
...state,
isFetchingUsers: false,
users: action.payload,
};
case types.FETCH_USERS_FAILURE:
return {
...state,
isFetchingUsers: false,
users: null,
};
default:
return state;
}
};
- After:
const reducer = (state = appInitialState, action) => reducerMatching(
[ types.INC_COUNT, incrementCounter ],
[ types.DEC_COUNT, decrementCounter ],
[ types.INC_TEN_COUNT, sumTenToCounter ],
[ types.DEC_TEN_COUNT, subTenToCounter ],
[ types.FETCH_USERS, fetchUsers ],
[ types.FETCH_USERS_SUCCESS, fetchUsersSuccess ],
[ types.FETCH_USERS_FAILURE, fetchUsersFailure ]
)(state, action);
- More examples and documentation