Skip to content

Commit

Permalink
Merge pull request #296 from Workiva/handle-useRef-null
Browse files Browse the repository at this point in the history
FED-3209 Remove explicit null passed to useRef
  • Loading branch information
rmconsole5-wk authored Oct 1, 2024
2 parents 3c1a681 + e7f232a commit 8fef280
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:codemod/codemod.dart';
import 'package:collection/collection.dart';

/// Suggestor that finds instances of `useRef` function invocations that
/// pass an argument, and replaces them with `useRefInit` to prep for
Expand All @@ -24,9 +25,11 @@ import 'package:codemod/codemod.dart';
///
/// ```dart
/// // Before
/// final ref = useRef(someNonNulLValue);
/// final ref1 = useRef(someNonNulLValue);
/// final ref2 = useRef<Element>(null);
/// // After
/// final ref = useRefInit(someNonNulLValue);
/// final ref1 = useRefInit(someNonNulLValue);
/// final ref2 = useRef<Element>();
/// ```
class UseRefInitMigration extends RecursiveAstVisitor
with AstVisitingSuggestor {
Expand All @@ -44,8 +47,14 @@ class UseRefInitMigration extends RecursiveAstVisitor
}

if (fnName == 'useRef') {
yieldPatch('useRefInit', possibleInvocation.function.offset,
possibleInvocation.function.end);
final argument = node.arguments.singleOrNull;
if (argument is NullLiteral) {
// Remove unnecessary null argument
yieldPatch('', argument.offset, argument.end);
} else {
yieldPatch('useRefInit', possibleInvocation.function.offset,
possibleInvocation.function.end);
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,5 +104,25 @@ void main() {
'''),
);
});

test('removes unnecessary null arguments', () async {
await testSuggestor(
expectedPatchCount: 2,
input: withOverReactImport('''
useTestHook() {
final foo = useRef(null);
final bar = useRef<String>(null);
return [foo, bar];
}
'''),
expectedOutput: withOverReactImport('''
useTestHook() {
final foo = useRef();
final bar = useRef<String>();
return [foo, bar];
}
'''),
);
});
});
}

0 comments on commit 8fef280

Please sign in to comment.