javascript - How to implement a dynamic reducer creator for API service call in React with Redux project? -


since may have many api services call, have write many reducers these services, there way implement reducer creators dynamically below?

const pending = 'pending' const rejected = 'rejected' const fulfilled = 'fulfilled' const companies = 'companies'  let createreducer = (name) => (state, action) => {   switch (action.type) {     case name + '_' + pending:       return {...state,          isloading: false       }     case name + '_' + fulfilled:       return {...state,          companies: action.payload,         isloading: false       }     case name + '_' + rejected:       return {...state,          isloading: false,         err: action.payload       }     default:       return state   } }  let comapnyreducer = createreducer(companies) 

which can equivalent below explicit implementation:

const comapnyreducer = (state={isloading: false}, action) => { switch (action.type) {   case 'companies_pending':     return {...state,        isloading: false     }   case 'companies_fulfilled':     return {...state,        companies: action.payload,       isloading: false     }   case 'companies_rejected':     return {...state,        isloading: false,       err: action.payload     }   default:     return state   } } 

goal of example illustrate how might be. implementation may different in details.

demo jsbin

const pending = 'pending' const rejected = 'rejected' const fulfilled = 'fulfilled'  const reducer = (state={isloading:false}, action) => {   const {name, type} = action;   switch (type) {     case name + '_' + pending:       return {...state, isloading: false }     case name + '_' + fulfilled:       return {...state,         items: action.payload,         isloading: false       }     case name + '_' + rejected:       return {...state,         isloading: false,         err: action.payload       }     default:       return state   } }  const entities = (state={},action)=>{   if(action.name){     const name = action.name.tolowercase()     return {...state, [name]:reducer(state[name],action)  }   }else{      return state   } } 

action example

{type:'companies_fulfilled',name:'companies',payload:[1,2,3,4]} 

result

    "companies": {         "items": [             1,             2,             3,             4         ],         "isloading": false     },     "messages": {         "items": [             1,             2,             3,             4         ],         "isloading": false     } 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -