ffxsam ffxsam - 2 months ago 16
React JSX Question

Cleaner/shorter way to update nested state in Redux?

Sometimes reducers get kind of messy:

const initialState = {
notificationBar: {
open: false,
},
};

export default function (state = initialState, action) {
switch (action.type) {
case actions.LAYOUT_NOTIFICATIONBAR_OPEN:
return Object.assign({}, state, {
// TODO: Find a cleaner way to do this!
notificationBar: Object.assign({}, state.notificationBar, {
open: true,
}),
});
default:
return state;
}
}


Is there a more terse way to do this?

Answer

It might be slightly improved via a non-standardised yet properties spread operator:

return {
    ...state,
    notificationBar: {
        ...state.notificationBar,
        open: true,
    },
};