I have a onClick() method for a PrimaryButton class. I got @typescript-eslint/no-misused-promises error from eslint check. Code as below:
onClick = { () =>
Utils.getName(a, b).then(
(name) => {
Utils.deleteThing(name, x, y);
})
}
How should I fix my code to avoid this error? Would appreciate your help. Thanks!
Update: eslint config as follows
Error message is on the line of onClick():
CodePudding user response:
The error states that a void return was expected. But instead, you are returning a promise.
onClick = { () =>
Utils.getName(a, b).then(
(name) => {
Utils.deleteThing(name, x, y);
})
}
The way you write your arrow function, you are returning the below code (a promise) rather than running it and just returning nothing:
Utils.getName(a, b).then(
(name) => {
Utils.deleteThing(name, x, y);
})
However, if you write your code like this, void is returned and the code is actually ran:
onClick = { () => {
Utils.getName(a, b).then(
(name) => {
Utils.deleteThing(name, x, y);
})
}
}
The key is how an arrow function works. If you leave out the {
}
after the =>
, the return is implied to be the single statement after the =>
which is not what you wanted. You didn't want to return the Utils.getName
function, you just wanted it to run. See here for more info.