1
votes

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:

  1. Create reducer user = combineReducers(..., photos, ...)
  2. Create actionCreator updateUser

    const updateUser = (id, subAction) => ({
        type: UPDATE_USER,
        payload: {
            id,
            subAction
        }
    })

  1. 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
        }
    }

  1. 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?

1

1 Answers

0
votes

Why not simply dispatch both in the place where this is initiated by the user?

dispatch(updateUser(id));
dispatch(addPhoto(url));

I haven't come across this pattern you're applying before. It seems a bit unusual that one reducer is responsible for reducing state of another. Creates a dependency between them that doesn't feel very pure. I'm not even sure one reducer should be able to/can see the state of another.

So no idea about "correct", but I'd say it's not ideal to do it your way. I'd try dispatching both sequentially or maybe in a sort of meta-action that takes care of nested updates and dispatches actions to multiple reducers.