Reduction reduces the pattern for actions and gear

I am trying to figure out what is the best practice for this situation.

2 context: SPORT todos and HOME todos.

so there are 2 action files:

export const SPORT_ADD_TODO = `[SPORT] ADD TODO`
export const HOME_ADD_TODO = `[HOME] ADD TODO`

and 2 file reducers

homeReducer(state, action) {
  switch(action.type) {
     case HOME_ADD_TODO:
        return Object.assing({}, state, {
           todos: action.payload
        })
     default:
        return state;
  }
}

sportReducer(state, action) {
      ....
}

is there an official solution for this situation? I do not want to repeat myself. gearbox has the same functionality

+4
source share
3 answers

you need to think about your application architecture again. In general, a reusable gearbox / action is incorrect.

why is this wrong? at present, it seems surprising that you can write reusable gearboxes and actions that are less stereotyped, rather than DRY. in the example of your application. "ADD_TO_DO" are equal for home and sport.

, , / add_to_do. . . ( if, , , //).

, , 2 2 . , .

+1

, , . Redux - , Javascript. factory.

createTodoReducer factory:

function createTodoReducer(initialState, {addType}) {
  return function(state = initialState, action) {
    switch(action.type) {
      case addType:
        return {...state, todos: action.payload}
    }
  }
}

factory sportTodosReducer homeReducer:

const homeReducer = createTodosReducer({todos: []}, {addType: 'HOME_ADD_TODO'});
const sportsReducer = createTodoReducer({todos: []}, {addType: 'SPORTS_ADD_TODO'})

, addType, factory.

+1

Take a look at Redux Actions , which is a library with helper functions to reduce the pattern for both actions and reducers.

0
source

Source: https://habr.com/ru/post/1691423/


All Articles