javascriptredux

Can I return new copy of only part of a state object instead of the entire state object


I have the following initial state that consists of flat properties and one deep nested property searchStatus:

var searchStatus = Immutable.fromJS({
    requesting: {
        component: {tenants: false, platforms: false},
        tenant: false,
        hdf: false,
        cluster: false
    }
});

const initialState = {
    selectedItem: null,
    searchQuery: '',
    searchStatus: searchStatus
};

I have a reducer that works with this state:

function reducer(state = initialState, action) {
        switch (action.type) {
            case GET_TENANT_TEMPLATES_LISTING_REQUEST:
                var status = state.searchStatus.updateIn(['requesting', 'component', 'tenants'], function () {
                    return true;
                });
                return assign({}, state, {
                    searchStatus: status
                });

Is it OK to return new copy only for searchStatus part of the state and then merge it into the state or should I always return the entire state copy?

UPDATE:

case GET_TENANT_TEMPLATES_LISTING_REQUEST:
    var copy = assign({}, state);
    copy.searchStatus.requesting.component.tenants = true;
    return copy;

Solution

  • You must copy the state object over every time (note that internal references can be kept, so it's not as inefficient as you may think), which is what you're doing with your assign (which I can only assume is a shorthand for Object.assign())

    Your call to assign will copy over all of the properties from state, and then from { searchStatus: status }, to an empty object, effectively copying over your entire state, and then applying changes.

    You must not mutate the state passed into the function, and you must also return a complete state object from the function.