How to fix Eslint error "prefer-destructuring"?

Timo picture Timo · Nov 20, 2017 · Viewed 37.4k times · Source

I wanted to shorten an object literal in ES6 like this:

const loc = this.props.local;

The reason is loc.foo(); is a lot easier to type than this.props.local.foo();

But now ESLint complains:

Use object destructuring: prefer-destructuring

I've read the error description on eslint.org but I don't understand it. They have an example which looks very similar to my code but theirs seem to be ok?

var foo = object.bar;

How can I fix the error without setting it to ignore in the .eslintrc file?

Answer

Badis Merabet picture Badis Merabet · Nov 20, 2017

change your code from:

const local = this.props.local;

to:

const { local } = this.props;

They are equivalent and you can call local.foo() in the same way. except that the second use object destructuring.