Skip to content

Commit

Permalink
fix(class-to-function): Fixes #75
Browse files Browse the repository at this point in the history
  • Loading branch information
Boris Litvinsky committed Aug 5, 2019
1 parent 02483f4 commit 42b9493
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/modules/stateful-to-stateless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ export function statefulToStateless(component) {
ClassMethod(path) {
if (isHooksForFunctionalComponentsExperimentOn()) {
const methodName = path.node.key.name;
if (!lifecycleMethods.includes(methodName)) {
if (!lifecycleMethods.includes(methodName) && methodName !== "render") {
nonLifeycleMethodsPresent = true;
}
if (path.node.kind === "constructor") {
Expand Down Expand Up @@ -415,27 +415,37 @@ export async function statefulToStatelessComponent() {
const persistantChanges = [
replaceSelectionWith(selectionProccessingResult.text)
];
if (selectionProccessingResult.metadata.stateHooksPresent) {
persistantChanges.push(importHook("useState"));
}

if (selectionProccessingResult.metadata.nonLifeycleMethodsPresent) {
persistantChanges.push(importHook("useCallback"));
const {
stateHooksPresent,
nonLifeycleMethodsPresent
} = selectionProccessingResult.metadata;
const usedHooks = [
...(stateHooksPresent ? ["useState"] : []),
...(nonLifeycleMethodsPresent ? ["useCallback"] : [])
];

if (usedHooks.length) {
persistantChanges.push(importHooks(...usedHooks));
}

await persistFileSystemChanges(...persistantChanges);
}
} catch (e) {
handleError(e);
}

function importHook(name) {
function importHooks(...hooks) {
const currentFile = activeURI().path;
const file = readFileContent(currentFile);
const ast = codeToAst(file);
const reactImport = getReactImportReference(ast);
reactImport.specifiers.push(
t.importSpecifier(t.identifier(name), t.identifier(name))
);
hooks.forEach(hook => {
reactImport.specifiers.push(
t.importSpecifier(t.identifier(hook), t.identifier(hook))
);
});

const updatedReactImport = transformFromAst(t.program([reactImport])).code;
return replaceTextInFile(
updatedReactImport,
Expand Down

0 comments on commit 42b9493

Please sign in to comment.