Kvoti / redux-rest

Automatically create Redux action constants, action creators, and reducers for your REST API
MIT License
180 stars 11 forks source link

How do I write a custom reducer? #17

Open bhoomit opened 8 years ago

bhoomit commented 8 years ago

In some cases I want to pre-process the API result before I save it to store. I've made few changes to make this work. If you think its a good feature to have, I can send a PR.

mallison commented 8 years ago

Being able to override the default reducer seems like a sensible idea. Please do submit a PR and I'll take a look. Thanks.

bhoomit commented 8 years ago

Take a look at this code:

import API from 'redux-rest'
import { ItemReducer, itemStatus } from 'redux-rest'

const myAPI = {
  users: '/api/users/',
  xyz: '/api/xyz/'
}      

const api = new API(myAPI)

// custom reducer
class XYZReducer extends ItemReducer {
  _reducer (state = [], action) {
    if(action.type == 'xyz_list_success') {
      // do something to the result
      // action.payload = <processed payload> 
      return action.payload
    }
    return state
  }
}

api.reducers.xyz_items = new XYZReducer(api.actionTypes.xyz).getReducer()

export default api