Skip to content

Commit

Permalink
Fix ESLint rule crash (#15044)
Browse files Browse the repository at this point in the history
  • Loading branch information
gaearon committed Mar 7, 2019
1 parent 9b7e1d1 commit 6d2666b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,17 @@ const tests = {
}
`,
},
{
// Regression test for a crash
code: `
function Podcasts() {
useEffect(() => {
setPodcasts([]);
}, []);
let [podcasts, setPodcasts] = useState(null);
}
`,
},
],
invalid: [
{
Expand Down Expand Up @@ -3812,6 +3823,32 @@ const tests = {
'Either include it or remove the dependency array.',
],
},
{
// Regression test for a crash
code: `
function Podcasts() {
useEffect(() => {
alert(podcasts);
}, []);
let [podcasts, setPodcasts] = useState(null);
}
`,
// Note: this autofix is shady because
// the variable is used before declaration.
// TODO: Maybe we can catch those fixes and not autofix.
output: `
function Podcasts() {
useEffect(() => {
alert(podcasts);
}, [podcasts]);
let [podcasts, setPodcasts] = useState(null);
}
`,
errors: [
`React Hook useEffect has a missing dependency: 'podcasts'. ` +
`Either include it or remove the dependency array.`,
],
},
],
};

Expand Down
12 changes: 11 additions & 1 deletion packages/eslint-plugin-react-hooks/src/ExhaustiveDeps.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,17 @@ export default {
}
// Detect primitive constants
// const foo = 42
const declaration = def.node.parent;
let declaration = def.node.parent;
if (declaration == null) {
// This might happen if variable is declared after the callback.
// In that case ESLint won't set up .parent refs.
// So we'll set them up manually.
fastFindReferenceWithParent(componentScope.block, def.node.id);
declaration = def.node.parent;
if (declaration == null) {
return false;
}
}
if (
declaration.kind === 'const' &&
init.type === 'Literal' &&
Expand Down

0 comments on commit 6d2666b

Please sign in to comment.