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

[ESLint] Disallow hooks in async functions #27045

Merged
merged 1 commit into from
Jul 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1042,6 +1042,22 @@ const tests = {
`,
errors: [classError('useState')],
},
{
code: normalizeIndent`
async function AsyncComponent() {
useState();
}
`,
errors: [asyncComponentHookError('useState')],
},
{
code: normalizeIndent`
async function useAsyncHook() {
useState();
}
`,
errors: [asyncComponentHookError('useState')],
},
],
};

Expand Down Expand Up @@ -1300,6 +1316,14 @@ if (__EXPERIMENTAL__) {
`,
errors: [classError('use')],
},
{
code: normalizeIndent`
async function AsyncComponent() {
use();
}
`,
errors: [asyncComponentHookError('use')],
},
];
}

Expand Down Expand Up @@ -1368,6 +1392,12 @@ function useEffectEventError(fn) {
};
}

function asyncComponentHookError(fn) {
return {
message: `React Hook "${fn}" cannot be called in an async function.`,
};
}

// For easier local testing
if (!process.env.CI) {
let only = [];
Expand Down
11 changes: 11 additions & 0 deletions packages/eslint-plugin-react-hooks/src/RulesOfHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,17 @@ export default {
// Pick a special message depending on the scope this hook was
// called in.
if (isDirectlyInsideComponentOrHook) {
// Report an error if the hook is called inside an async function.
const isAsyncFunction = codePathNode.async;
if (isAsyncFunction) {
context.report({
node: hook,
message:
`React Hook "${context.getSource(hook)}" cannot be ` +
'called in an async function.',
});
}

// Report an error if a hook does not reach all finalizing code
// path segments.
//
Expand Down