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 Dec 8, 2021
1 parent a5b1f2b commit 292bbbb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
23 changes: 17 additions & 6 deletions lib/rules/hook-use-state.js
Expand Up @@ -54,7 +54,7 @@ module.exports = {
? useStateReactImportSpecifier.local.name
: undefined;

const isReactUseStateCall = (
const isPotentialReactUseStateCall = (
defaultReactImportName
&& node.callee.type === 'MemberExpression'
&& node.callee.object.type === 'Identifier'
Expand All @@ -69,17 +69,28 @@ module.exports = {
&& node.callee.name === useStateReactImportName
);

const scope = isPotentialUseStateCall && context.getScope();
const useStateReference = scope && scope.references.find(
const scope = isPotentialReactUseStateCall || isPotentialUseStateCall
? context.getScope()
: undefined;

const reactResolvedDefs = isPotentialReactUseStateCall && scope.references.find(
(reference) => reference.identifier.name === defaultReactImportName
).resolved.defs;
const useStateResolvedDefs = isPotentialUseStateCall && scope.references.find(
(reference) => reference.identifier.name === useStateReactImportName
);
const useStateResolvedDefs = useStateReference
? useStateReference.resolved.defs
).resolved.defs;

const ultimateReactResolvedDef = reactResolvedDefs
? reactResolvedDefs[reactResolvedDefs.length - 1]
: undefined;
const ultimateUseStateResolvedDef = useStateResolvedDefs
? useStateResolvedDefs[useStateResolvedDefs.length - 1]
: undefined;

const isReactShadowed = ultimateReactResolvedDef && ultimateReactResolvedDef.type !== 'ImportBinding';
const isUseStateShadowed = ultimateUseStateResolvedDef && ultimateUseStateResolvedDef.type !== 'ImportBinding';

const isReactUseStateCall = isPotentialReactUseStateCall && !isReactShadowed;
const isUseStateCall = isPotentialUseStateCall && !isUseStateShadowed;

// Ignore unless this is a useState() or React.useState() call.
Expand Down
14 changes: 13 additions & 1 deletion tests/lib/rules/hook-use-state.js
Expand Up @@ -91,13 +91,25 @@ const tests = {
{
code: `import { useState } from 'react'
function useState() { // shadows React's useState
return null;
return null
}
export default function useColor() {
const result = useState()
}`,
features: ['no-default'],
},
{
code: `import React from 'react'
const React = {
useState: () => {
return null
}
}
export default function useColor() {
const result = React.useState()
}`,
features: ['no-default'],
},
{
code: `import { useState } from 'react'
export default function useColor() {
Expand Down

0 comments on commit 292bbbb

Please sign in to comment.