Skip to content

Commit 7992ca1

Browse files
authored
eslint-plugin-react-hooks: allow OptionalMemberExpression in deps (facebook#18819) (facebook#18820)
* eslint-plugin-react-hooks: allow OptionalMemberExpression in deps (facebook#18819) * add test case for facebook#18819 * fix test * run prettier
1 parent e028ce2 commit 7992ca1

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1755,6 +1755,38 @@ const tests = {
17551755
},
17561756
],
17571757
},
1758+
{
1759+
code: normalizeIndent`
1760+
function MyComponent({ history }) {
1761+
useEffect(() => {
1762+
return [
1763+
history?.foo
1764+
];
1765+
}, []);
1766+
}
1767+
`,
1768+
errors: [
1769+
{
1770+
message:
1771+
"React Hook useEffect has a missing dependency: 'history?.foo'. " +
1772+
'Either include it or remove the dependency array.',
1773+
suggestions: [
1774+
{
1775+
desc: 'Update the dependencies array to be: [history?.foo]',
1776+
output: normalizeIndent`
1777+
function MyComponent({ history }) {
1778+
useEffect(() => {
1779+
return [
1780+
history?.foo
1781+
];
1782+
}, [history?.foo]);
1783+
}
1784+
`,
1785+
},
1786+
],
1787+
},
1788+
],
1789+
},
17581790
{
17591791
code: normalizeIndent`
17601792
function MyComponent() {

packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1429,7 +1429,8 @@ function scanForDeclaredBareFunctions({
14291429
*/
14301430
function getDependency(node) {
14311431
if (
1432-
node.parent.type === 'MemberExpression' &&
1432+
(node.parent.type === 'MemberExpression' ||
1433+
node.parent.type === 'OptionalMemberExpression') &&
14331434
node.parent.object === node &&
14341435
node.parent.property.name !== 'current' &&
14351436
!node.parent.computed &&
@@ -1456,6 +1457,7 @@ function getDependency(node) {
14561457
* (foo) -> 'foo'
14571458
* foo.(bar) -> 'foo.bar'
14581459
* foo.bar.(baz) -> 'foo.bar.baz'
1460+
* foo?.(bar) -> 'foo?.bar'
14591461
* Otherwise throw.
14601462
*/
14611463
function toPropertyAccessString(node) {
@@ -1465,6 +1467,10 @@ function toPropertyAccessString(node) {
14651467
const object = toPropertyAccessString(node.object);
14661468
const property = toPropertyAccessString(node.property);
14671469
return `${object}.${property}`;
1470+
} else if (node.type === 'OptionalMemberExpression' && !node.computed) {
1471+
const object = toPropertyAccessString(node.object);
1472+
const property = toPropertyAccessString(node.property);
1473+
return `${object}?.${property}`;
14681474
} else {
14691475
throw new Error(`Unsupported node type: ${node.type}`);
14701476
}

0 commit comments

Comments
 (0)