Skip to content

Commit

Permalink
Add support for variables too
Browse files Browse the repository at this point in the history
  • Loading branch information
MattisAbrahamsson committed May 3, 2024
1 parent b1f6219 commit 6f5bcd1
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/rules/noUsePrefixForNonHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,42 @@ export const noUsePrefixForNonHook = ESLintUtils.RuleCreator.withoutDocs({
return;
}

context.report({
node,
messageId: "noUsePrefixForNonHook",
});
},
VariableDeclaration(node) {
const declaration = node.declarations[0];

if (!declaration) {
return;
}

const name =
"name" in declaration.id ? declaration?.id.name : "";

if (!name || !hasUsePrefix(name)) {
return;
}

// Check if the variable is assigned an arrow function
if (
declaration.init &&
declaration.init.type === "ArrowFunctionExpression"
) {
// We check arrow functions in the ArrowFunctionExpression visitor
return;
}

if (
declaration.init &&
declaration.init.type === "Identifier" &&
hasUsePrefix(declaration.init.name)
) {
return;
}

context.report({
node,
messageId: "noUsePrefixForNonHook",
Expand Down
27 changes: 27 additions & 0 deletions src/tests/noUsePrefixForNonHook.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ ruleTester.run("noUsePrefixForNonHook", noUsePrefixForNonHook, {
"function useCustom() {useEffect(() => {});}",
"function myFunction() {}",
"function userFunction() {}",
"const user = null;",
"const myVariable = null;",
"const data = useUserData();",
],
invalid: [
{
Expand Down Expand Up @@ -78,5 +81,29 @@ ruleTester.run("noUsePrefixForNonHook", noUsePrefixForNonHook, {
},
],
},
{
code: "const useCustom = null;",
errors: [
{
messageId: "noUsePrefixForNonHook",
},
],
},
{
code: "function myFunction() {}; const useCustom = myFunction;",
errors: [
{
messageId: "noUsePrefixForNonHook",
},
],
},
{
code: "const myVariable = null; const useCustom = myVariable;",
errors: [
{
messageId: "noUsePrefixForNonHook",
},
],
},
],
});

0 comments on commit 6f5bcd1

Please sign in to comment.