eslint-plugin-react-hooks: allow OptionalMemberExpression in deps (#18819) (#18820)

* eslint-plugin-react-hooks: allow OptionalMemberExpression in deps (#18819)

* add test case for #18819

* fix test

* run prettier
This commit is contained in:
Kevin Lewis
2020-05-05 13:53:42 +01:00
committed by GitHub
parent e028ce2ab7
commit 7992ca10df
2 changed files with 39 additions and 1 deletions
@@ -1755,6 +1755,38 @@ const tests = {
},
],
},
{
code: normalizeIndent`
function MyComponent({ history }) {
useEffect(() => {
return [
history?.foo
];
}, []);
}
`,
errors: [
{
message:
"React Hook useEffect has a missing dependency: 'history?.foo'. " +
'Either include it or remove the dependency array.',
suggestions: [
{
desc: 'Update the dependencies array to be: [history?.foo]',
output: normalizeIndent`
function MyComponent({ history }) {
useEffect(() => {
return [
history?.foo
];
}, [history?.foo]);
}
`,
},
],
},
],
},
{
code: normalizeIndent`
function MyComponent() {
@@ -1429,7 +1429,8 @@ function scanForDeclaredBareFunctions({
*/
function getDependency(node) {
if (
node.parent.type === 'MemberExpression' &&
(node.parent.type === 'MemberExpression' ||
node.parent.type === 'OptionalMemberExpression') &&
node.parent.object === node &&
node.parent.property.name !== 'current' &&
!node.parent.computed &&
@@ -1456,6 +1457,7 @@ function getDependency(node) {
* (foo) -> 'foo'
* foo.(bar) -> 'foo.bar'
* foo.bar.(baz) -> 'foo.bar.baz'
* foo?.(bar) -> 'foo?.bar'
* Otherwise throw.
*/
function toPropertyAccessString(node) {
@@ -1465,6 +1467,10 @@ function toPropertyAccessString(node) {
const object = toPropertyAccessString(node.object);
const property = toPropertyAccessString(node.property);
return `${object}.${property}`;
} else if (node.type === 'OptionalMemberExpression' && !node.computed) {
const object = toPropertyAccessString(node.object);
const property = toPropertyAccessString(node.property);
return `${object}?.${property}`;
} else {
throw new Error(`Unsupported node type: ${node.type}`);
}