Skip to content

Commit

Permalink
Increase performance by getting rid of unneeed updates in calculatedE…
Browse files Browse the repository at this point in the history
…xpression. Closes #81
  • Loading branch information
ruscoder committed Oct 10, 2024
1 parent fc07701 commit 3a305e8
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions sdc-qrf/src/components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@ import { QuestionnaireItem } from 'shared/src/contrib/aidbox';

import { useQuestionnaireResponseFormContext } from '.';
import { QRFContext } from './context';
import { ItemContext, QRFContextData, QuestionItemProps, QuestionItemsProps } from './types';
import {
FormAnswerItems,
ItemContext,
QRFContextData,
QuestionItemProps,
QuestionItemsProps,
} from './types';
import { calcContext, getBranchItems, getEnabledQuestions, wrapAnswerValue } from './utils';

export function usePreviousValue<T = any>(value: T) {
Expand Down Expand Up @@ -72,7 +78,9 @@ export function QuestionItem(props: QuestionItemProps) {
calcContext(initialContext, variable, branchItems.qItem, curQRItem),
)
: calcContext(initialContext, variable, branchItems.qItem, branchItems.qrItems[0]!);
const prevAnswers = usePreviousValue(_.get(formValues, fieldPath));
const prevAnswers: FormAnswerItems[] | undefined = usePreviousValue(
_.get(formValues, fieldPath),
);

useEffect(() => {
if (!isGroupItem(questionItem, context) && calculatedExpression) {
Expand All @@ -84,15 +92,20 @@ export function QuestionItem(props: QuestionItemProps) {
calculatedExpression.expression!,
context as ItemContext,
);
const newAnswers = newValues.length
const newAnswers: FormAnswerItems[] | undefined = newValues.length
? repeats
? newValues.map((answer: any) => ({
value: wrapAnswerValue(type, answer),
}))
: [{ value: wrapAnswerValue(type, newValues[0]) }]
: undefined;

if (!isEqual(newAnswers, prevAnswers)) {
if (
!isEqual(
newAnswers?.map((answer) => answer.value),
prevAnswers?.map((answer) => answer.value),
)
) {
const allValues = _.set(_.cloneDeep(formValues), fieldPath, newAnswers);
setFormValues(allValues, fieldPath, newAnswers);
}
Expand Down

0 comments on commit 3a305e8

Please sign in to comment.