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

[ESLint] Fix ESLint rule crash in an edge case #15044

Merged
merged 1 commit into from
Mar 7, 2019
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 @@ -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