aBloomer aBloomer - 1 month ago 4
Javascript Question

How do I only update one value of my reducer in Redux?

Below is my code

function customMsg(state, action) {
state = state || {
person: {
isFetching: false,
didInvalidate: false,
name: "",
height: "",
}
};

switch(action.type) {

case ACTION_TYPES.PERSON.FETCH_PERSOn_CONTENT_SUCCESS:
return $.extend({}, state, {
person.name: action.result.name
});

default:
return state;
}
}


How do I only update one value of my reducer in Redux?
Above is a example which i only want to update the name of person object.
How can i do that?

Answer

Using jQuery extend, create a clone and set person name:

var newState = $.extend({}, state);
newState.person.name = action.result.name;
return newState;

Otherwise, to clone deeply an object you can use lodash cloneDeep().

Another way is to use immutableJS to set you app state as immutable. It is much more bug "mutable" proof and offers functions to set deep nested value in an immutable like updateIn:

return state.updateIn(['person', 'name'], () => action.result.name);

Try it!