I'm wondering what is the right way to delete a nested field in redux actions. For example, I have this code:
const SUBSCRIBE = 'SUBSCRIBE';
const UNSUBSCRIBE = 'UNSUBSCRIBE';
export default function reducer(state = {}, action) {
const {
productName,
products,
componentName
} = action;
switch (action.type) {
case UNSUBSCRIBE: {
if (state[productName]?.[componentName]) {
const newState = { ...state };
delete newState[productName][componentName];
return newState;
} else {
return state;
}
}
default:
return state;
}
}
export function unsubscribe(productName, componentName) {
return {
type: UNSUBSCRIBE,
productName,
componentName
};
}
In UNSUBSCRIBE
action I delete newState[productName][componentName]
field, however this will also delete the field on the "old" state. So theoretically if there're other actions which use this field it may be lost for them because the state is mutated. Should I deep copy old state into newState
and then delete newState[productName][componentName]
?