Skip to content

Commit

Permalink
enhance no-use-state-initializer-functions rule to support conditiona…
Browse files Browse the repository at this point in the history
…l expressions with function calls
  • Loading branch information
rezkiy37 committed Dec 3, 2024
1 parent 86151f0 commit fa4c5fd
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
8 changes: 6 additions & 2 deletions eslint-plugin-expensify/no-use-state-initializer-functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,12 @@ module.exports = {

const firstArg = node.arguments[0];

// Return early if the first argument is not a function call or a member expression with a function call
// Return early if the first argument is not a function call, member expression with a function call, or conditional expression with function calls
if (
firstArg.type !== 'CallExpression'
&& !(firstArg.type === 'MemberExpression' && firstArg.object.type === 'CallExpression')
&& !(firstArg.type === 'ConditionalExpression'
&& (firstArg.consequent.type === 'CallExpression' || firstArg.alternate.type === 'CallExpression'))
) {
return;
}
Expand Down Expand Up @@ -64,10 +66,12 @@ module.exports = {
return; // Valid case, do nothing
}

// If it's a direct function call or a member expression with a function call, report it
// If it's a direct function call, member expression with a function call, or conditional expression with function calls, report it
if (
firstArg.type === 'CallExpression'
|| (firstArg.type === 'MemberExpression' && firstArg.object.type === 'CallExpression')
|| (firstArg.type === 'ConditionalExpression'
&& (firstArg.consequent.type === 'CallExpression' || firstArg.alternate.type === 'CallExpression'))
) {
context.report({
node: firstArg,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ ruleTester.run('no-use-state-initializer-functions', rule, {
useState(() => testFunc().value);
`,
},
{
// Calling a callback should be valid
code: `
useState(condition ? testFunc : testFunc);
`,
},
{
// Calling a callback should be valid
code: `
useState(condition ? () => testFunc() : () => testFunc());
`,
},
],
invalid: [
{
Expand All @@ -47,5 +59,27 @@ ruleTester.run('no-use-state-initializer-functions', rule, {
},
],
},
{
// Calling a function should be invalid
code: `
useState(condition ? testFunc() : testFunc());
`,
errors: [
{
message,
},
],
},
{
// Calling a function should be invalid
code: `
useState(condition ? (() => testFunc())() : (() => testFunc())());
`,
errors: [
{
message,
},
],
},
],
});

0 comments on commit fa4c5fd

Please sign in to comment.