- Notifications
You must be signed in to change notification settings - Fork0
A functional redux utility to replace the switch case statement.
License
NotificationsYou must be signed in to change notification settings
IsTheJack/reducer-matching
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A functional redux util to replace the switch case statement.
Get the pattern below as alternative to switch case statement.
ThereducerMatching 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
varreducerMatch:[string,function]=[types.INC_COUNT,(state,action)=>'do something...'];
In case of no matches, the reducer matching will return the state without changes.
importreducerMatchingfrom'reducer-matching';constinitialState={};constreducer=(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 reducersfunctionfetchUsersSuccess(state,action){return{ ...state,isFetchingUsers:false,users:action.payload,};}// ... other reducersexportdefaultreducer;
The tests was make in Jest.
npm run testAny PR is welcome! :D
- Ramda - A practical functional library for JavaScript programmers.
- Before:
constreducer=(state=appInitialState,action)=>{switch(action.type){casetypes.INC_COUNT:return{ ...state,count:state.count+1};casetypes.DEC_COUNT:return{ ...state,count:state.count-1};casetypes.INC_TEN_COUNT:return{ ...state,count:state.count+10};casetypes.DEC_TEN_COUNT:return{ ...state,count:state.count-10};casetypes.FETCH_USERS:return{ ...state,isFetchingUsers:true};casetypes.FETCH_USERS_SUCCESS:return{ ...state,isFetchingUsers:false,users:action.payload,};casetypes.FETCH_USERS_FAILURE:return{ ...state,isFetchingUsers:false,users:null,};default:returnstate;}};
- After:
constreducer=(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
About
A functional redux utility to replace the switch case statement.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published
Uh oh!
There was an error while loading.Please reload this page.