skip to Main Content

I have a react application that is giving a linting error:

Promise-returning function provided to attribute
where a void return was expected
.eslint@typescript-eslint/no-misused-promises

The function looks like this

      <Button onClick={
        async () => {
          await handleDelete()
        }}
      >

I’ve tried adding return void along with a number of different ways to wrap the code and add catch as suggested in various SO posts but none of them worked to resolve the error.

I do not wish to disable the rule without understanding why – and once I do it will probably be to remove or disable the rule in the lint config

2

Answers


  1. There are two approaches here:

    1. You could either wrap the function in an IIFE (Immediately Invoked Function Expression),
         <Button onClick={
             () => {
                 void (async () => {
                     await handleDelete()
                 })();
              }
          }>
    

    You can learn more about IIFE on: MDN Official Docs

    1. Or, you could disable the no-misused-promises rule.

    For project wide, add rule in .eslintrc:

    {
      "@typescript-eslint/no-misused-promises": [
        "error",
        {
          "checksVoidReturn": false
        }
      ]
    }
    

    To disable this inline, comment this above the particular occurrence to ignore the error.

    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    

    You could read about it more on: GitHub ESLint Docs

    Login or Signup to reply.
  2. In this particular case you can safely skip using async, because there is no need for either handleDelete result or async flow control

          <Button onClick={
            () => {
              handleDelete()
            }}
          >
    

    In other scenarios the documentation for the no-misused-promises rule suggests 2 approaches:

    • Use an async IIFE wrapper
          <Button onClick={
            () => {
              void (async () => {
                await handleDelete();
              })();
            }}
          >
    
    • Name the async wrapper to call it later
          <Button onClick={
            () => {
              const handle = async () => {
                await handleDelete()
              }
              handle()
            }}
          >
    

    ref: https://typescript-eslint.io/rules/no-misused-promises/#checksvoidreturn

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search