Skip to content

Commit

Permalink
refactor(EditableDetails): optimize form handling with useMemo (#3048)
Browse files Browse the repository at this point in the history
- Replace direct defaultValues assignment with memoized formValues
- Remove unnecessary useEffect for form reset on data change
- Simplify conditional rendering logic in the return statement

Co-authored-by: Alon Peretz <[email protected]>
  • Loading branch information
shanegrouber and alonp99 authored Feb 11, 2025
1 parent 351d0bb commit d0029e7
Showing 1 changed file with 15 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
useCallback,
useEffect,
useState,
useMemo,
} from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { toTitleCase } from 'string-ts';
Expand Down Expand Up @@ -125,13 +126,16 @@ export const EditableDetails: FunctionComponent<IEditableDetails> = ({

return isDecisionComponent && !!value && NEGATIVE_VALUE_INDICATOR.includes(value.toLowerCase());
};
const defaultValues = data?.reduce((acc, curr) => {
acc[curr.title] = curr.value;
const formValues = useMemo(() => {
return data?.reduce((acc, curr) => {
acc[curr.title] = curr.value;

return acc;
}, {});
}, [data]);

return acc;
}, {});
const form = useForm({
defaultValues,
values: formValues,
});
const { mutate: mutateUpdateWorkflowById } = useUpdateDocumentByIdMutation({
directorId,
Expand Down Expand Up @@ -249,11 +253,6 @@ export const EditableDetails: FunctionComponent<IEditableDetails> = ({
data,
});

// Ensures that the form is reset when the data changes from other instances of `useUpdateWorkflowByIdMutation` i.e. in `useCaseCallToActionLogic`.
useEffect(() => {
form.reset(defaultValues);
}, [form.reset, data]);

return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className={`flex h-full flex-col`}>
Expand Down Expand Up @@ -281,7 +280,9 @@ export const EditableDetails: FunctionComponent<IEditableDetails> = ({
const originalValue = form.watch(title);

const displayValue = (value: unknown) => {
if (isEditable) return originalValue;
if (isEditable) {
return originalValue;
}

return isNullish(value) || value === '' ? 'N/A' : value;
};
Expand All @@ -299,7 +300,9 @@ export const EditableDetails: FunctionComponent<IEditableDetails> = ({
control={form.control}
name={title}
render={({ field }) => {
if (isDecisionComponent && !value) return null;
if (isDecisionComponent && !value) {
return null;
}

const isInput = [
!checkIsUrl(value) || isEditable,
Expand Down

0 comments on commit d0029e7

Please sign in to comment.