Skip to content

Commit

Permalink
fix(linter/react): fix false positives for async components in `rules…
Browse files Browse the repository at this point in the history
…_of_hooks` (#3307)

related to #3257
  • Loading branch information
rzvxa committed May 16, 2024
1 parent 0864cd0 commit 712ee0d
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions crates/oxc_linter/src/rules/react/rules_of_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,18 +149,6 @@ impl Rule for RulesOfHooks {
id.name.as_str(),
));
}
// Hooks can't be called from async function.
AstKind::Function(Function { id: Some(id), r#async: true, .. }) => {
return ctx.diagnostic(diagnostics::async_component(id.span, id.name.as_str()));
}
// Hooks can't be called from async arrow function.
AstKind::ArrowFunctionExpression(ArrowFunctionExpression {
span,
r#async: true,
..
}) => {
return ctx.diagnostic(diagnostics::async_component(*span, "Anonymous"));
}
// Hooks are allowed inside of unnamed functions used as arguments. As long as they are
// not used as a callback inside of components or hooks.
AstKind::Function(Function { id: None, .. }) | AstKind::ArrowFunctionExpression(_)
Expand All @@ -173,7 +161,11 @@ impl Rule for RulesOfHooks {
return;
}
AstKind::Function(Function { span, id: None, .. })
| AstKind::ArrowFunctionExpression(ArrowFunctionExpression { span, .. }) => {
| AstKind::ArrowFunctionExpression(ArrowFunctionExpression {
span,
r#async: false,
..
}) => {
let ident = get_declaration_identifier(nodes, parent_func.id());

// Hooks cannot be called inside of export default functions or used in a function
Expand Down Expand Up @@ -206,6 +198,18 @@ impl Rule for RulesOfHooks {
));
}
}
// Hooks can't be called from async function.
AstKind::Function(Function { id: Some(id), r#async: true, .. }) => {
return ctx.diagnostic(diagnostics::async_component(id.span, id.name.as_str()));
}
// Hooks can't be called from async arrow function.
AstKind::ArrowFunctionExpression(ArrowFunctionExpression {
span,
r#async: true,
..
}) => {
return ctx.diagnostic(diagnostics::async_component(*span, "Anonymous"));
}
_ => {}
}

Expand Down Expand Up @@ -923,6 +927,13 @@ fn test() {
};
};
",
"
test.beforeEach(async () => {
timer = Sinon.useFakeTimers({
toFake: ['setInterval'],
});
});
",
];

let fail = vec![
Expand Down

0 comments on commit 712ee0d

Please sign in to comment.