From 24ec0b308cfda0eb0c3faacb5648aeefd7eb52f0 Mon Sep 17 00:00:00 2001 From: Duncan Beevers Date: Wed, 21 Apr 2021 01:48:31 -0700 Subject: [PATCH] fixup! [New] Symmetric useState hook variable names --- lib/rules/hook-use-state.js | 19 +++++++++++-------- tests/lib/rules/hook-use-state.js | 13 ++++++++++--- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/rules/hook-use-state.js b/lib/rules/hook-use-state.js index fdd6247f29..57f9ec6633 100644 --- a/lib/rules/hook-use-state.js +++ b/lib/rules/hook-use-state.js @@ -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. @@ -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) => ( @@ -112,7 +115,7 @@ module.exports = { ) : undefined; - reactUseStateLocal = reactUseStateSpecifier + reactUseStateLocalName = reactUseStateSpecifier ? reactUseStateSpecifier.local.name : undefined; } diff --git a/tests/lib/rules/hook-use-state.js b/tests/lib/rules/hook-use-state.js index 3b4ca5200a..970a5f08a1 100644 --- a/tests/lib/rules/hook-use-state.js +++ b/tests/lib/rules/hook-use-state.js @@ -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' }]