Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-hooks/exhaustive-deps: Handle optional chained methods as dependency (#20204) #20247

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3593,6 +3593,36 @@ const tests = {
},
],
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {}, [props?.attribute.method()]);
}
`,
errors: [
{
message:
'React Hook useEffect has a complex expression in the dependency array. ' +
'Extract it to a separate variable so it can be statically checked.',
suggestions: undefined,
AriPerkkio marked this conversation as resolved.
Show resolved Hide resolved
},
],
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {}, [props.method()]);
}
`,
errors: [
{
message:
'React Hook useEffect has a complex expression in the dependency array. ' +
'Extract it to a separate variable so it can be statically checked.',
suggestions: undefined,
},
],
},
{
code: normalizeIndent`
function MyComponent() {
Expand Down
5 changes: 5 additions & 0 deletions packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -1643,6 +1643,11 @@ function analyzePropertyChain(node, optionalChains) {
return result;
} else if (node.type === 'ChainExpression' && !node.computed) {
const expression = node.expression;

if (expression.type === 'CallExpression') {
throw new Error(`Unsupported node type: ${expression.type}`);
}

const object = analyzePropertyChain(expression.object, optionalChains);
const property = analyzePropertyChain(expression.property, null);
const result = `${object}.${property}`;
Expand Down