Last active
May 5, 2021 21:17
-
-
Save elderbas/70722378373885c1aea7d4381d5e7069 to your computer and use it in GitHub Desktop.
codemodscript to refactor `useEffect` with empty array to `useEffectOnce` without an array arg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function (file, api) { | |
const j = api.jscodeshift; | |
const { CallExpression, Identifier } = j; | |
return ( | |
j(file.source) | |
.find(CallExpression, { | |
callee: { | |
name: "useEffect", | |
}, | |
}) | |
.filter((node) => { | |
return ( | |
// is a useEffect with 2 arguments | |
node.value.arguments.length === 2 && | |
// 2nd argument is an array type | |
node.value.arguments[1].type === "ArrayExpression" && | |
// said array argument is an empty array | |
node.value.arguments[1].elements.length === 0 | |
); | |
}) | |
// operate on useEffects that have an empty dependency array | |
.forEach((node) => { | |
// refactor the function name | |
node.value.callee.name = "useEffectOnce"; | |
// remove the 2nd argument to this function | |
node.value.arguments = [node.value.arguments[0]]; | |
}) | |
.toSource() | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment