Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(EditableDetails): optimize form handling with useMemo #3048

Merged
merged 5 commits into from
Feb 11, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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