C
C
cester2018-02-07 12:16:41
JavaScript
cester, 2018-02-07 12:16:41

How can the High Order Reducer be improved?

Good afternoon! Can you please tell me how this High Order Reducer can be improved ?

const funcReducer = (type, initState, name, payload) =>
  (state = initState, action = {}) => {
    switch (action.type) {
      case type[0]:
        return {
          [name]: {
            ...state[name],
            data: payload ? action.payload[payload] : state[name].data,
          },
        };
      case type[1]:
        return {
          [name]: {
            ...state[name],
            isOpen: true,
            data: !action.payload ? state[name].data : action.payload[payload],
          },
        };
      case type[2]:
        return {
          [name]: {
            ...state[name],
            isOpen: false,
            error: '',
          },
        };
      case type[3]:
        return {
          [name]: {
            ...state[name],
            isLoading: true,
            error: '',
          },
        };
      default:
        return state;
    }
  };
export default funcReducer ;

const types = [
  '',
  'OPEN_MODAL',
  'CLOSE_MODAL',
  'DELETE_REQUEST',
];

export const deleteItemReducer = funcReducer(types, initialState, 'delete', 'item');

The problem is that, for example
data: !action.payload ? state[name].data : action.payload[payload]
is not needed everywhere.
I would be grateful for any help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2018-02-07
@cester

In my practice, such things only confuse the code. If you ask me, as they say, I would write it for several reducers myself. Easier to read, easier to maintain.
I believe that code should be written for people, not for a machine.

D
davidnum95, 2018-02-07
@davidnum95

It all depends on what you wanted to achieve with this code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question