For example we have reducer photos
, which handles array of photos via actions ADD_PHOTO
and REMOVE_PHOTO
. And if we have arrays users
and posts
, they both have field for array of photos.
So, in order to avoid code duplicates I'm going to do the following:
- Create reducer
user = combineReducers(..., photos, ...)
- Create actionCreator
updateUser
const updateUser = (id, subAction) => ({ type: UPDATE_USER, payload: { id, subAction } })
- Create reducer
users
(Here I'm using Immutable.js)
function users(state = List(), action) { switch (action.type) { //... case UPDATE_USER: const { id, subAction } = action.payload const index = state.findIndex(user => user.id == id) return state.updateIn( [index, 'photos'], state => photos(state, subAction) ) break //... default: return state } }
And then I'm going to use all of it like this:
dispatch(updateUser(id, addPhoto(url)))
Is this a correct solution of my problem?