Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust options for @typescript-eslint/no-misused-promises to allow promises as JSX attributes #15

Closed
codybrouwers opened this issue May 2, 2022 · 3 comments
Labels

Comments

@codybrouwers
Copy link
Member

We are currently using the default options of this recommended rule @typescript-eslint/no-misused-promises, but it results in errors trying to pass functions that return promises as React props to components that are only expecting a () => void type, including built in React event handlers like onClick.

image

This fix for this is to update the options for the rule disable checking void returns for attributes like this:

  "@typescript-eslint/no-misused-promises": [
    "error",
    {
      "checksVoidReturn": {
        "arguments": false,
        "attributes": true
      }
    }
  ]
@mrmckeb
Copy link
Contributor

mrmckeb commented May 2, 2022

Thanks @codybrouwers. I can definitely see where this will be helpful - I've hit this before too.

My only concern is that this rule helps prevent unhandled promise rejections. A component that expects a promise would be able to catch an error.

Users could solve this by either a) making components handle async functions and/or b) using promises instead of making the callback a promise.

// Before
const loadMore = async () => {
  try {
    const thing = await getSomethingAsync();
    await doSomethingAsync(thing);
  } catch (e) {
    /* .. */
  }
}

// After
const loadMore = () => {
  getSomethingAsync()
    .then(doSomethingAsync)
    .catch(/* ... */)
}

It would be great to get some more input/thoughts on this IMO.

@mrmckeb
Copy link
Contributor

mrmckeb commented Sep 21, 2022

We've closed this in favour of a util that wraps these functions, removing the risk of any uncaught exceptions.

@mrmckeb mrmckeb closed this as completed Sep 21, 2022
@codybrouwers
Copy link
Member Author

For reference the util we're using is:

import { captureError } from '@lib/report-error';

/**
 * Wraps and handles a promise, catching any errors and reporting those to
 * our error tracking tool
 *
 * This utility is particularly useful when trying to resolve
 * `@typescript-eslint/no-misused-promises`.
 *
 * @param asyncFn - Any async function to wrap
 */
export function promiseToCallback<
  T extends (...args: never[]) => Promise<unknown>,
>(asyncFn: T) {
  return (...args: Parameters<T>) => {
    asyncFn(...args).catch((error) => captureError(error));
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants