C
C
cester2018-01-31 18:33:16
JavaScript
cester, 2018-01-31 18:33:16

How to use High-Order-Reducer, react/redux?

Good afternoon! I'm trying to rewrite the reducer using High-Order-Reducer, until I quite understand how to optimize it so as not to make it worse.
For example, there is such a reducer (which can be many times larger)

const createAsyncReducer (state, action) => {
  switch (action.type) {
    case "USER_REQUEST":
      return {
        ...state,
        isFetching: true
      }
    case "USER_SUCCESS":
      return {
        ...state,
        isFetching: false,
        data: action.payload,
        error: void 0,
      }
    case  "USER_FAILURE":
      return {
        ...state,
        isFetching: false,
        error: action.payload
      }
      case  "USER_SOME_ACTION":
      return {
        ...state,
        isFetching: false,
        error: action.payload.some
      }
    default: return state;
  }
}

and found such an entry through High-Order. The question is how can it be improved further?
const createAsyncReducer = (constants) => (state, action) => {
  switch (action.type) {
    case constants[0]:
      return {
        ...state,
        isFetching: true
      }
    case constants[1]:
      return {
        ...state,
        isFetching: false,
        data: action.payload,
        error: void 0,
      }
    case constants[2]:
      return {
        ...state,
        isFetching: false,
        error: action.payload
      }
    default: return state;
  }
}
const todosReducer = createAsyncReducer([
  "TODOS_REQUEST",
  "TODOS_SUCCESS",
  "TODOS_FAILURE"
]);

const withAddTodo = reducer => (state, action) => {
  const nextState = reducer(state, action);
  switch (action.type) {
    case "ADD_TODO":
      return {
        ...nextState,
        data: [...nextState.data, action.payload]
      };
    default:
      return nextState;
  }
};

const customReducer = withAddTodo(todosReducer);

The code has only grown from this ...
Please tell us who has what experience with this and best practices for optimizing this.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-01-31
@Gentlee

The best redux optimization is to use my redux-light library :). And no more reducers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question