Skip to content

Commit

Permalink
fixup! [New] Symmetric useState hook variable names
Browse files Browse the repository at this point in the history
  • Loading branch information
duncanbeevers committed Apr 21, 2021
1 parent 2bfe443 commit 24ec0b3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
19 changes: 11 additions & 8 deletions lib/rules/hook-use-state.js
Expand Up @@ -32,24 +32,24 @@ module.exports = {
},

create(context) {
let isReactImported = false;
let reactUseStateLocal;
let reactImportLocalName;
let reactUseStateLocalName;

return {
CallExpression(node) {
const isReactUseStateCall = (
isReactImported
reactImportLocalName
&& node.callee.type === 'MemberExpression'
&& node.callee.object.type === 'Identifier'
&& node.callee.object.name === 'React'
&& node.callee.object.name === reactImportLocalName
&& node.callee.property.type === 'Identifier'
&& node.callee.property.name === 'useState'
);

const isUseStateCall = (
reactUseStateLocal
reactUseStateLocalName
&& node.callee.type === 'Identifier'
&& node.callee.name === reactUseStateLocal
&& node.callee.name === reactUseStateLocalName
);

// Ignore unless this is a useState() or React.useState() call.
Expand Down Expand Up @@ -102,7 +102,10 @@ module.exports = {
}
},
ImportDeclaration(node) {
isReactImported = node.source.type === 'Literal' && node.source.value === 'react';
const isReactImported = node.source.type === 'Literal' && node.source.value === 'react';
const reactDefaultSpecifier = node.specifiers.find((specifier) => specifier.type === 'ImportDefaultSpecifier');
reactImportLocalName = reactDefaultSpecifier ? reactDefaultSpecifier.local.name : undefined;

const reactUseStateSpecifier = isReactImported
? node.specifiers.find(
(specifier) => (
Expand All @@ -112,7 +115,7 @@ module.exports = {
)
: undefined;

reactUseStateLocal = reactUseStateSpecifier
reactUseStateLocalName = reactUseStateSpecifier
? reactUseStateSpecifier.local.name
: undefined;
}
Expand Down
13 changes: 10 additions & 3 deletions tests/lib/rules/hook-use-state.js
Expand Up @@ -91,15 +91,22 @@ const tests = {
}]
},
{
code: `import { useState } from 'react';
const result = useState()`,
code: `import React from 'react';
const result = React.useState()`,
errors: [{
message: 'setState call is not destructured into value + setter pair'
}]
},
{
code: `import ReactAlternative from 'react';
ReactAlternative.useState()`,
errors: [{
message: 'setState call is not destructured into value + setter pair'
}]
},
{
code: `import { useState } from 'react';
const result = React.useState()`,
const result = useState()`,
errors: [{
message: 'setState call is not destructured into value + setter pair'
}]
Expand Down

0 comments on commit 24ec0b3

Please sign in to comment.