Skip to content

Commit

Permalink
[Fix] hook-use-state: Allow UPPERCASE setState setter prefixes
Browse files Browse the repository at this point in the history
  • Loading branch information
duncanbeevers authored and ljharb committed Mar 14, 2022
1 parent 73ad445 commit cab6943
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 5 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,11 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange

## Unreleased

### Fixed
* [`hook-use-state`]: Allow UPPERCASE setState setter prefixes ([#3244][] @duncanbeevers)

[#3244]: https://github.com/yannickcr/eslint-plugin-react/pull/3244

## [7.29.4] - 2022.03.13

### Fixed
Expand Down
18 changes: 13 additions & 5 deletions lib/rules/hook-use-state.js
Expand Up @@ -66,23 +66,31 @@ module.exports = {
? setterVariable.name
: undefined;

const expectedSetterVariableName = valueVariableName ? (
`set${valueVariableName.charAt(0).toUpperCase()}${valueVariableName.slice(1)}`
) : undefined;
const caseCandidateMatch = valueVariableName ? valueVariableName.match(/(^[a-z]+)(.*)/) : undefined;
const upperCaseCandidatePrefix = caseCandidateMatch ? caseCandidateMatch[1] : undefined;
const caseCandidateSuffix = caseCandidateMatch ? caseCandidateMatch[2] : undefined;
const expectedSetterVariableNames = upperCaseCandidatePrefix ? [
`set${upperCaseCandidatePrefix.charAt(0).toUpperCase()}${upperCaseCandidatePrefix.slice(1)}${caseCandidateSuffix}`,
`set${upperCaseCandidatePrefix.toUpperCase()}${caseCandidateSuffix}`,
] : [];

const isSymmetricGetterSetterPair = valueVariable
&& setterVariable
&& setterVariableName === expectedSetterVariableName
&& expectedSetterVariableNames.indexOf(setterVariableName) !== -1
&& variableNodes.length === 2;

if (!isSymmetricGetterSetterPair) {
const suggestions = [
{
desc: 'Destructure useState call into value + setter pair',
fix: (fixer) => {
if (expectedSetterVariableNames.length === 0) {
return;
}

const fix = fixer.replaceTextRange(
node.parent.id.range,
`[${valueVariableName}, ${expectedSetterVariableName}]`
`[${valueVariableName}, ${expectedSetterVariableNames[0]}]`
);

return fix;
Expand Down
27 changes: 27 additions & 0 deletions tests/lib/rules/hook-use-state.js
Expand Up @@ -35,6 +35,33 @@ const tests = {
}
`,
},
{
code: `
import { useState } from 'react'
function useRGB() {
const [rgb, setRGB] = useState()
return [rgb, setRGB]
}
`,
},
{
code: `
import { useState } from 'react'
function useRGBValue() {
const [rgbValue, setRGBValue] = useState()
return [rgbValue, setRGBValue]
}
`,
},
{
code: `
import { useState } from 'react'
function useCustomColorValue() {
const [customColorValue, setCustomColorValue] = useState()
return [customColorValue, setCustomColorValue]
}
`,
},
{
code: `
import { useState } from 'react'
Expand Down

0 comments on commit cab6943

Please sign in to comment.