Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Object Destructuring Default Values for Nested Parameters

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?

like image 451
glcheetham Avatar asked Mar 17 '17 11:03

glcheetham


1 Answers

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};
}
like image 54
Bergi Avatar answered Sep 20 '22 08:09

Bergi