let
variables are block scoped and the entire switch
body is one block.
You can move your deconstructive assignment line to the start:
export default (state = initialState, action) => {
switch (action.type) {
let { text, field } = action.payload;
let newState = { ...state };
case CHANGE_LOGIN_CREDENTIALS_FIELD:
newState.inputs[field].content = text;
return newState;
case CHANGE_LOGIN_CREDENTIALS_FIELD:
newState.inputs[field].focused = true;
return newState;
default:
return state;
}
};
This works if you have (roughly) the same logic for each of those. And in this case you do - you always want field
from action.payload
and you sometimes need text
. So, if you take both, you can use one or both as appropriate. In addition, newState
is always { ...state }
and as a let
variable, you also need to avoid re-declaring it.
Another alternative is to put each case
into a block:
export default (state = initialState, action) => {
switch (action.type) {
case CHANGE_LOGIN_CREDENTIALS_FIELD: {
let { text, field } = action.payload;
let newState = { ...state };
newState.inputs[field].content = text;
return newState;
}
case FOCUS_CREDENTIALS_FIELD: {
let { field } = action.payload;
let newState = { ...state };
newState.inputs[field].focused = true;
return newState;
}
default:
return state;
}
};
This makes each case
a self-contained block, so you avoid clashes of let
variables between them.