简体   繁体   中英

Separation of concerns in reducers working in same action

I have the following normalized state shape that I want to implement.

{
    userAccounts: {
        byId: {
            "1234": {
                "id": "1234",
                "name": "Obi-wan",
                "gender": "Male",
                "age": 40
            },
            "4321": {
                "id": "4321",
                "name": "Padme",
                "gender": "Female",
                "age": 26
            },
            ...
        },
        allIds: ["1234", "4321", ...]
    }
}

This is the action that fetches data to get user accounts.

export const getAccounts = () => {
  return (dispatch) => {
    dispatch({type: GET_ACCOUNTS_REQUEST});
    return API.getAccountsList(session).then(
      (response) => {
        dispatch({
          type: GET_ACCOUNTS_SUCCESS,
          payload: response
        })
      },
      (error) => {
        ...
      }
    )
  };
};

The payload contains a key called accounts and this key contains an array among other non relevant fields.

payload: {
  accounts: [ { ... }, { ... } ],
  ...
}

My reducer waits for the action GET_ACCOUNTS_SUCCESS and I use combineReducers.

[GET_USERS_SUCCESS]: (state, action) => {
    return combineReducers({
      byId,
      allIds
    });
}

My current implementation of the reducer is like this:

const byId = (state, action) => {
  const { accounts } =  action.payload;
  const nextState = {
    byId: {},
    allIds: []
  };
  accounts.map(account => {
    nextState.byId[account.id] = {
      ...account
    };
    nextState.allIds = [
      ...nextState.allIds,
      account.id
    ]
  });
  return nextState;
};

I would like to separate this reducers into two to have better separation of concerns avoiding to do two maps.

Any idea?

You could create two new reducers listening to two new actions SET_ACCOUNT_BY_ID and SET_ACCOUNT_BY_ALL_IDS (as an example) which are dispatched by the GET_ACCOUNTS_SUCCESS action. When dispatching these two actions, you can pass in only the required data to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM