A gear that returns a collection of gear results

I have a reducer that looks like this:

const chart = combineReducers({
    data,   
    fetchProgress,
    fetchError,
    updateProgress,
    updateError,
});

Now I want not only a diagram, but also a few diagrams.

const charts = (state = {}, action = {}) => {
    if (action.type == FETCH_CHART || action.type == ...) { 
        let newChart = chart(state[action.id], action);
        return Object.assign({}, state, {[action.id]: newChart});
    }
    return state;
}

Is there anything fundamentally wrong for this?

If not, is there a better way to achieve the same result?

+4
source share
2 answers

There is nothing wrong with the concept. In fact, I would say that this is my preferred approach when you need to store such data in a redux store

To improve it, you can wrap it in a gear of a higher order to process part of it id. Sort of:

const handleIds = (reducer) => (state = {}, action) => {
    if (action.id) {
        let idState = state[action.id]
        let newState = reducer(idState, action)

        if (newState !== idState) {
            return  { ...state, [action.id]: newState }
        }
    }

    return state
}

id state state id , state .

:

const singleChart = (state = {}, action = {}) => {
    if (action.type == FETCH_CHART || action.type == ...) { 
        let newChart = chart(state, action);
        return newChart;
    }
    return state;
}

const charts = handleIds(singleChart)

:

const chart = combineReducers({
    data,   
    fetchProgress,
    fetchError,
    updateProgress,
    updateError,
    charts
});
+1

, . , , // , .

, 3 .

// bubbleChartReducer.js
export function bubble (state = {}, action) {
  switch (action.type) {
    case 'FETCH_BUBBLE_CHART': 
      return {
        [action.id]: new chart(action.id, action)
      }
    default:
      return state
  }
}

// pieChartReducer.js
export function pie (state = {}, action) {
  switch (action.type) {
    case 'FETCH_PIE_CHART': 
      return {
        [action.id]: new chart(action.id, action)
      }
    default:
      return state
  }
}

// linearChartReducer.js
export function pie (state = {}, action) {
  switch (action.type) {
    case 'FETCH_LINEAR_CHART': 
      return {
        [action.id]: new chart(action.id, action)
      }
    default:
      return state
  }
}



// chartsReducer.js
import { bubble } from 'bubbleChartReducer'
import { pie } from 'pieChartReducer'
import { linear } from 'linearChartReducer'
import { combineReducers } from 'redux'

export combineReducers({
  bubble,
  pie,
  linear
})
+1

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


All Articles