0

I have a lot of fields in user form, and SonarLint display a message

"Refactor this function to reduce its Cognitive Complexity"

How can I do this, move each field in separate component? in this case I have to send formik a s parameter for everyone, maybe there are another options?

interface IUserFormData {
    firstName?: string;
    lastName?: string;
    //and 20 more fields
}
interface IUserFormProps {
    isEdit: boolean;
    userData: IUserFormData;
}
   
const ManageUserForm = ({isEdit, userData}: IUserFormProps) => {
        const formik = useFormik({
        initialValues: {
            firstName: userData.firstName,
            lastName: userData.lastName,
            //and 20 more fields...
            }

return(
        <form
            onSubmit = { formik.handleSubmit }
            id = { isEdit? 'update-user-form': 'create-user-form' } > //cognitive complexity if

            <TextField
                id="firstName"
                label='First Name'
                defaultValue={formik.values.firstName}
                onChange={formik.handleChange}
                error={formik.touched.firstName && Boolean(formik.errors.firstName)} //cognitive complexity if
                helperText={formik.touched.firstName && formik.errors.firstName} //cognitive complexity if
            />
            <TextField
                id="lastName"
                label='Last Name'
                defaultValue={formik.values.lastName}
                onChange={formik.handleChange}
                error={formik.touched.lastName && Boolean(formik.errors.lastName)} //cognitive complexity if
                helperText={formik.touched.lastName && formik.errors.lastName} //cognitive complexity if
            />
            //and 20 more fields
        </form >

        .....
Alex
  • 8,908
  • 28
  • 103
  • 157
  • 1
    Does this answer your questions? https://stackoverflow.com/questions/62815733/refactor-this-method-to-reduce-its-cognitive-complexity-from-21-to-the-15-allowe – bicarlsen Apr 28 '22 at 07:57
  • 1
    @bicarlsen yeah, moved everything in functions and fixed congnitive complexity – Alex Apr 28 '22 at 10:52

0 Answers0