I'm using es6 object destructuring to provide default parameters to a function.
function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) {
return {
CakeShopName: shops.cakeShop.Name,
PieShopName: shops.pieShop.Name
}
}
The problem with the above is that if I call
mapStateToProps({})
The code throws Cannot read property 'Name' of undefined
. The nested objects on shops
are not set to their default values and the code has a null reference.
How can I make sure that the nested objects within shops
are being set to the right default value, even if shops
itself is defined?
Sound like you were confusing destructuring with default values. Your syntax destructures an argument object, but doesn't actually introduce any parameter identifiers. There is no shops
variable in your function scope.
I'll assume that you actually wanted to introduce cakeShop
and pieShop
variables, and provide them with defaults. To do that, you'd write
function mapStateToProps({ shops: { cakeShop = {}, pieShop = {} }) {
// short for { shops: { cakeShop: cakeShop = {}, pieShop: pieShop = {} }) {
// parameter names (that will be bound): ^^^^^^^^ ^^^^^^^
return {
CakeShopName: cakeShop.Name,
PieShopName: pieShop.Name
}
}
You might also use
function mapStateToProps({ shops: { cakeShop: {name: CakeShopName} = {}, pieShop: {name: PieShopName} = {} }) {
return {CakeShopName, PieShopName};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With