Skip to content

Instantly share code, notes, and snippets.

@lukasMega
Forked from dgcoffman/require-named-effect.js
Created December 1, 2022 10:25
Show Gist options
  • Save lukasMega/3334339bd6e86917811d9a3b4e0ca7b3 to your computer and use it in GitHub Desktop.
Save lukasMega/3334339bd6e86917811d9a3b4e0ca7b3 to your computer and use it in GitHub Desktop.
libs/eslint-rules/require-named-effect.js
const isUseEffect = (node) => node.callee.name === 'useEffect';
const argumentIsArrowFunction = (node) => node.arguments[0].type === 'ArrowFunctionExpression';
const effectBodyIsSingleFunction = (node) => {
const { body } = node.arguments[0];
// It's a single unwrapped function call:
// `useEffect(() => theNameOfAFunction(), []);`
if (body.type === 'CallExpression') {
return true;
}
// There's a function body, but it just calls another function:
// `useEffect(() => {
// theOnlyChildIsAFunctionCall();
// }, []);`
if (body.body?.length === 1 && body.body[0]?.expression?.type === 'CallExpression') {
return true;
}
return false;
};
const fail = (report, node) => report(node, 'Complex effects must be a named function.');
module.exports = {
create(context) {
return {
CallExpression(node) {
if (
isUseEffect(node) &&
argumentIsArrowFunction(node) &&
!effectBodyIsSingleFunction(node)
) {
fail(context.report, node);
}
},
};
},
};
const rule = require('./require-named-effect');
const ruleTester = require('./helpers/ruleTester');
describe('require-named-effect', () => {
const valid = [
`useEffect(function namedFunction() {}, []);`,
`useEffect(theNameOfAFunction(), []);`,
`useEffect(() => theNameOfAFunction(), []);`,
`useEffect(() => {
theOnlyChildIsAFunctionCall();
}, []);`,
];
const invalid = [
`useEffect(() => {}, []);`,
`useEffect(() => {
const t = 1;
diallowTwoThings(t);
}, []);`,
];
ruleTester.run('require-named-effect', rule, {
valid,
invalid: invalid.map((code) => ({
code,
errors: ['Complex effects must be a named function.'],
})),
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment