0

What I need: a way of accessing a destructured (or spread?) parameter by name.

My code is as follows:

open = ({ title = "Confirm", subTitle, link = {} } = {}) => {
    this.setState({ isVisible: true, ...params?? });
}

So basically I'm receiving a single object with properties a,b,c having default values for properties a,c.

After this, I want to spread the received object into my state (or for any other purpose). But.. I don't know what to spread..

So let's assume I'm trying to call it params as in the example.

What I tried:

open = (params : { title = "Confirm", subTitle, link = {} } = {}) => {

^ Unexpected token error


open = ({ title = "Confirm", subTitle, link = {} } = {} : params) => {

^ , expected


this.setState({ isVisible: true, ...arguments }); (attempt to access ES5 arguments object)

^'arguments' is not allowed in class field initializer' error


Is there any way of achieving this?

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
  • Are you asking how to name the whole argument **and** destructure it, simultaneously, in the parameter definition? If so: you can't do that, just move the destructuring *inside* the function, and it's a duplicate of https://stackoverflow.com/q/29051011/3001761. – jonrsharpe Aug 24 '18 at 12:14
  • 1
    Don't spread then in the argument list, but inside the function spread it? – Arup Rakshit Aug 24 '18 at 12:14
  • 3
    Why not just *not* use the spread in the function formal parameter list? Then you'll have a named reference to the entire original object, and you can then spread to your heart's content into local variables or whatever. – Pointy Aug 24 '18 at 12:14
  • 1
    I have the same issue. Was hoping one day we'd have: `({ title, sub, link } = source ) => { ... }` or similar, but atm, you destructure inside the function body. – Shilly Aug 24 '18 at 12:16
  • 1
    Yeah, after doing some more research I agree with you this is not possible since the object was already spread. – iuliu.net Aug 24 '18 at 12:16
  • Also @Pointy, how would I handle default values then? – iuliu.net Aug 24 '18 at 12:17
  • You can use default values in simple object-to-variable(s) destructuring assignment. – Pointy Aug 24 '18 at 12:19
  • @Pointy: but they wouldn't be reflected in `namedReference`, is what I think he means. – Amadan Aug 24 '18 at 12:20
  • Ok but then I'm still not able to spread the received config object into my state.. I would have to write each variable individually. – iuliu.net Aug 24 '18 at 12:20

1 Answers1

0

There is no object you could spread after destructuring. (Well, there's arguments[0], but that's the actual argument not a new object containing the default values of your parameters).

You will want to explicitly use all the variables that you destructured into to form the new object:

function open({title = "Confirm", subTitle, link = {}} = {}) {
    this.setState({ isVisible: true, title, subTitle, link });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375