Skip to content

Commit

Permalink
fix: append async keyword when replace async func with useCallback
Browse files Browse the repository at this point in the history
  • Loading branch information
fossamagna committed Oct 4, 2024
1 parent eba4e58 commit dbbc18e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
28 changes: 28 additions & 0 deletions __tests__/require-usecallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,34 @@ describe('Rule - Require-usecallback', () => {
}`,
errors: [{ messageId: "function-usecallback-props" }, { messageId: "function-usecallback-props" }],
},
{
code: `
const Component = () => {
const myFn = async function test() {};
return <Child prop={myFn} />;
}`,
output: `import { useCallback } from 'react';
const Component = () => {
const myFn = useCallback(async () => {}, []);
return <Child prop={myFn} />;
}`,
errors: [{ messageId: "function-usecallback-props" }],
},
{
code: `
const Component = () => {
const myFn = async () => [];
return <Child prop={myFn} />;
}`,
output: `import { useCallback } from 'react';
const Component = () => {
const myFn = useCallback(async () => [], []);
return <Child prop={myFn} />;
}`,
errors: [{ messageId: "function-usecallback-props" }],
},
],
});
});
2 changes: 1 addition & 1 deletion src/require-usememo/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ function fixFunction(node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpre
const { body, params = [] } = node;
const funcBody = sourceCode.getText(body as ESTree.Node);
const funcParams = (params as Array<ESTree.Node>).map(node => sourceCode.getText(node));
let fixedCode = `useCallback((${funcParams.join(', ')}) => ${funcBody}, [])${shouldSetName ? ';' : ''}`
let fixedCode = `useCallback(${node.async ? 'async ' : ''}(${funcParams.join(', ')}) => ${funcBody}, [])${shouldSetName ? ';' : ''}`
if (shouldSetName && node?.id?.name) {
const name = node?.id?.name;
fixedCode = `const ${name} = ${fixedCode}`;
Expand Down

0 comments on commit dbbc18e

Please sign in to comment.