This is a general JavaScript question, although it just is used in React / Redux.
The code:
const connectedComponent = connect(
state => ({
noodleCount: state.noodleCount,
drinkCount: state.drinkCount,
snackCount: state.snackCount
})
)(TotalPrice);
seems a bit verbose, because it is using noodleCount
, state.noodleCount
repeatedly, so I refactored the code to:
const connectedComponent = connect(
state => {
const { noodleCount, drinkCount, snackCount } = state;
return { noodleCount, drinkCount, snackCount };
}
)(TotalPrice);
The line const { noodleCount, drinkCount, snackCount } = state;
made it much more concise, but the next line, I again have to repeat those names, and not only that, have to re-compose the object. Is there a way to make it better, such as being able just to do a return newState;
?
P.S. I tried in Node REPL:
> const state = { foo: 1, bar: 2, wah: 3}
undefined
> const newState = {foo, bar} = state;
undefined
> newState
{ foo: 1, bar: 2, wah: 3 }
so unfortunately, newState
did not just pick foo
and bar
but got wah
too. I also tried
const connectedComponent = connect(
state => {
const newState = { noodleCount, drinkCount, snackCount } = state;
return newState;
}
)(TotalPrice);
which is similar to the code in Node REPL above, but it gave
'noodleCount' is not defined no-undef