Tuesday, December 31, 2019

Redux - Spiltting Reducers



It is possible to split the todos into multiple functions for simplicity. For e.g. in the below, todoApp function.

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    case ADD_TODO:
      return Object.assign({}, state, {
        todos: [
          ...state.todos,
          {
            text: action.text,
            completed: false
          }
        ]
      })


In the above function, all of the todo list action related are taken care
While in the below, all of the visibility related items are taken care

function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [
        ...state,
        {
          text: action.text,
          completed: false
        }
      ]
    case TOGGLE_TODO:
      return state.map((todo, index) => {
        if (index === action.index) {
          return Object.assign({}, todo, {
            completed: !todo.completed
          })
        }
        return todo
      })

Now these two reducer functions can be combined in the below form

import { combineReducers } from 'redux'

const todoApp = combineReducers({
  visibilityFilter,
  todos
})


References:

No comments:

Post a Comment