rpivovar
rpivovar

Reputation: 3448

"Must use destructuring state assignment": How to destructure from object and place on property inside object literal

In a React project, I'm wanting to quickly troubleshoot things by logging specific parts of state at certain times.

console.error('this.state.thing', this.state.thing);

Doing this, My ESLint config gives me the error "Must use destructuring state assignment". So, I would have to either turn this ESLint rule off, or I would have to do this:

const { thing } = this.state;
console.error('this.state.thing', thing);

This is fine, but it made me wonder if I can destructure a property in the same way inside of an object literal in one go:

const objectLiteral = {
  thing: this.state.thing, // how to destructure thing out of state?
  stuff1,
  stuff2: otherData,
};

const somethingLikeThis = {
  thing: ({ thing } = this.state),
}

Just curious if there is a way to do this.

Upvotes: 1

Views: 435

Answers (2)

Felix Kling
Felix Kling

Reputation: 817238

Not inside the literal, but you can destructure values into object properties:

({thing: objectLiteral.thing} = this.state);

Upvotes: 1

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

Yes, you can do it through arrow function

console.error('this.state.thing', (obj => obj.thing)(this.state))

Upvotes: 1

Related Questions