Fix ESLint rule crash (#15044)

This commit is contained in:
Dan Abramov
2019-03-07 00:39:39 +00:00
committed by GitHub
parent b9dcd59bd0
commit acf8080b4b
2 changed files with 48 additions and 1 deletions
@@ -838,6 +838,17 @@ const tests = {
}
`,
},
{
// Regression test for a crash
code: `
function Podcasts() {
useEffect(() => {
setPodcasts([]);
}, []);
let [podcasts, setPodcasts] = useState(null);
}
`,
},
],
invalid: [
{
@@ -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.`,
],
},
],
};
@@ -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' &&