Reputation: 35950
I am using eslint rule react/destructuring-assignment
which throws. How can I destructure this?
getStuff(model = this.state.model) {
// some stuff
}
Upvotes: 1
Views: 3293
Reputation: 85545
ESLINT doesn't allow to use this.state.model
and it suggests you to utilize destructuring:
const { model: stateModel } = this.state
getStuff(model = stateModel) {
But, I'm afraid as it's inside react class component. Thus, you can't define a const or var before method definition. You should disable the eslint for the line:
getStuff(model = this.state.model) { // eslint-disable-line
Alternatively, you may use like:
getStuff(model) {
const { model: stateModel } = this.state
const passedModel = model ? model : stateModel
// then work through passedModel
}
Hmm, I can think of this should do the trick:
getStuff({state: {model}} = this) {
But, frankly I have never used such. Just try and let me know.
Update:
You may also use like:
getStuff(model) {
const { model: stateModel } = this.state || { model: model }
console.log(stateModel)
Or, simply:
getStuff(model) {
const { model } = this.state || { model }
// ----------------- similar to { model: model }
console.log(model)
Upvotes: 3
Reputation: 969
As I understand your need, you want to have a default var for a model from state and be able to pass it also if needed.
getStuff(passedModel) {
const { model } = this.state
const toUseModelInMethod = passedModel || model
// or
const toUseModelInMethod = passedModel ? passedModel : model
}
If you just want to get the model from this.state it's simple
getStuff() {
const { model } - this.state
}
Also you can pass your state to the method
getStuff({ model }) {...}
this.getStuff(this.state) // linter is not happy
// that's is better
getStuff(model){...}
const { model } = this.state
this.getStuff(model)
Upvotes: 1
Reputation: 4475
Your example isn't destructuring. A function would look like this:
function getStuff({ property1, property2 }) {
...
}
The above example would pull property1 and property2 from whatever object is passed to the given function.
Upvotes: 0