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

fix(eslint-plugin-react-hooks): Support nullish coalescing and optional chaining of dependencies #19008

Merged
merged 1 commit into from
May 27, 2020
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,44 @@ const tests = {
}
`,
},
// Nullish coalescing and optional chaining
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {
console.log(props.foo?.bar?.baz ?? null);
}, [props.foo]);
}
`,
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {
console.log(props.foo?.bar);
}, [props.foo?.bar]);
}
`,
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {
console.log(props.foo);
console.log(props.foo?.bar);
}, [props.foo]);
}
`,
},
{
code: normalizeIndent`
function MyComponent(props) {
useEffect(() => {
console.log(props.foo?.toString());
}, [props.foo]);
}
`,
},
{
code: normalizeIndent`
function MyComponent() {
Expand Down
19 changes: 17 additions & 2 deletions packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -1238,7 +1238,7 @@ function collectRecommendations({
const keys = path.split('.');
let node = rootNode;
for (const key of keys) {
let child = node.children.get(key);
let child = getChildByKey(node, key);
if (!child) {
child = createDepTree();
node.children.set(key, child);
Expand All @@ -1251,7 +1251,7 @@ function collectRecommendations({
const keys = path.split('.');
let node = rootNode;
for (const key of keys) {
const child = node.children.get(key);
const child = getChildByKey(node, key);
if (!child) {
return;
}
Expand All @@ -1260,6 +1260,21 @@ function collectRecommendations({
}
}

/**
* Match key with optional chaining
* key -> key
* key? -> key
* key -> key?
* Otherwise undefined.
*/
function getChildByKey(node, key) {
return (
node.children.get(key) ||
node.children.get(key.split('?')[0]) ||
node.children.get(key + '?')
);
}

// Now we can learn which dependencies are missing or necessary.
const missingDependencies = new Set();
const satisfyingDependencies = new Set();
Expand Down