ristepan
ristepan

Reputation: 45

Is this redux reducer OK

Is this reducer OK:

function someReducer(state = initialState, action) {
   if (action.type === SOME_ACTION) {
      const newState = Object.assign( {}, state );
      // ...
      // doing whatever I want with newState 
      // ...
      return newState;
   }   
   return state;
}

and if is OK, why we need all those immutable libraries to complicate our lives.

p.s Just trying to comprehend Redux and immutability

Upvotes: 1

Views: 315

Answers (4)

Nicolae Maties
Nicolae Maties

Reputation: 2655

export default function (state = initialState, action) {

  const actions = {
    SOME_ACTION: () => {
      return {
        ...state
      }
    },
    ANOTHER_ACTION: () => {
      return {
        ...state
        error: action.error
      }
    },
    DEFAULT: () => state;
  }
  
  return actions[action.type] ? actions[action.type]() : actions.DEFAULT(); 
}

I prefer doing this instead. I am not a big fan of switch statements.

Upvotes: 5

ristepan
ristepan

Reputation: 45

I found something that I really like:

 import createReducer from 'redux-starter-kit';
 const someReducer = createReducer( initialState, {
    SOME_ACTION: (state) => { /* doing whatever I want with this local State */ },
    SOME_ANOTHER_ACTION: (state) => { /* doing whatever I want with local State */ },
    THIRD_ACTION: (state, action) => { ... }, 
 });

Upvotes: 1

Mark
Mark

Reputation: 1679

The standard approach is to use a switch/case with spread syntax (...) in your reducer.

export default function (state = initialState, action) {
  switch (action.type) {
    case constants.SOME_ACTION:
      return {
        ...state,
        newProperty: action.newProperty
      };

    case constants.ERROR_ACTION:
      return {
        ...state,
        error: action.error
      };

    case constants.MORE_DEEP_ACTION:
      return {
        ...state,
        users: {
          ...state.users,
          user1: action.users.user1
        }
      };

    default:
      return {
        ...state
      }
  }
}

You can then use ES6 spread syntax to return your old state with whatever new properties you want changed/added to it.

You can read more about this approach here... https://redux.js.org/recipes/using-object-spread-operator

Upvotes: 3

Ashish
Ashish

Reputation: 4330

If your state has nested objects or arrays, Object.assign or ... will copy references to your older state variable and it may cause some issue. This is the reason why some developers use immutable libraries as in most of the case state has deep nested array or objects.

function someReducer(state = initialState, action) {
   if (action.type === SOME_ACTION) {
       const newState = Object.assign( {}, state );
       // newState can still have references to your older state values if they are array or orobjects

      return newState;
   }   
   return state;
}

Upvotes: -2

Related Questions