Skip to content

Commit

Permalink
fix(eslint-plugin-react-hooks): Added matching for nullish coalescing…
Browse files Browse the repository at this point in the history
… and optional chaining of dependencies, relates to #18985
  • Loading branch information
yanneves committed May 26, 2020
1 parent 67e130f commit 6faded2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
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

0 comments on commit 6faded2

Please sign in to comment.