@samitouri / QOS-React-2 / commits / 4821d609e9

fix(eslint-plugin-react-hooks): Added matching for nullish coalescing and optional chaining of dependencies, relates to #18985 (#19008)

Yann アウネ Eves committed May 27, 2020 at 01:07 UTC 4821d609e99f6bd6454279ee2a82448703d2f616
2 files changed +55 -2
packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
+38
@@ -251,6 +251,44 @@ const tests = {
251 }
252 `,
253 },
254 + // Nullish coalescing and optional chaining
255 + {
256 + code: normalizeIndent`
257 + function MyComponent(props) {
258 + useEffect(() => {
259 + console.log(props.foo?.bar?.baz ?? null);
260 + }, [props.foo]);
261 + }
262 + `,
263 + },
264 + {
265 + code: normalizeIndent`
266 + function MyComponent(props) {
267 + useEffect(() => {
268 + console.log(props.foo?.bar);
269 + }, [props.foo?.bar]);
270 + }
271 + `,
272 + },
273 + {
274 + code: normalizeIndent`
275 + function MyComponent(props) {
276 + useEffect(() => {
277 + console.log(props.foo);
278 + console.log(props.foo?.bar);
279 + }, [props.foo]);
280 + }
281 + `,
282 + },
283 + {
284 + code: normalizeIndent`
285 + function MyComponent(props) {
286 + useEffect(() => {
287 + console.log(props.foo?.toString());
288 + }, [props.foo]);
289 + }
290 + `,
291 + },
292 {
293 code: normalizeIndent`
294 function MyComponent() {
packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
+17 -2
@@ -1238,7 +1238,7 @@ function collectRecommendations({
1238 const keys = path.split('.');
1239 let node = rootNode;
1240 for (const key of keys) {
1241 - let child = node.children.get(key);
1241 + let child = getChildByKey(node, key);
1242 if (!child) {
1243 child = createDepTree();
1244 node.children.set(key, child);
@@ -1251,7 +1251,7 @@ function collectRecommendations({
1251 const keys = path.split('.');
1252 let node = rootNode;
1253 for (const key of keys) {
1254 - const child = node.children.get(key);
1254 + const child = getChildByKey(node, key);
1255 if (!child) {
1256 return;
1257 }
@@ -1260,6 +1260,21 @@ function collectRecommendations({
1260 }
1261 }
1262
1263 + /**
1264 + * Match key with optional chaining
1265 + * key -> key
1266 + * key? -> key
1267 + * key -> key?
1268 + * Otherwise undefined.
1269 + */
1270 + function getChildByKey(node, key) {
1271 + return (
1272 + node.children.get(key) ||
1273 + node.children.get(key.split('?')[0]) ||
1274 + node.children.get(key + '?')
1275 + );
1276 + }
1277 +
1278 // Now we can learn which dependencies are missing or necessary.
1279 const missingDependencies = new Set();
1280 const satisfyingDependencies = new Set();