Skip to content

Commit

Permalink
Use bindRecalculateFields to pass a closure
Browse files Browse the repository at this point in the history
This gets around the issue that eslint was
complaining about as the react hook is now at the
top level, and we pass a closure into it.
  • Loading branch information
awensaunders committed Oct 20, 2024
1 parent 7c47761 commit 5dffccc
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions app/javascript/components/record-form/form/record-form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ function RecordForm({
const formikValues = useRef();
const bindedSetValues = useRef(null);
const bindedResetForm = useRef(null);
const bindedRecalculateFields = useRef(null);

const bindSetValues = setValues => {
bindedSetValues.current = setValues;
Expand All @@ -64,6 +65,10 @@ function RecordForm({
bindedResetForm.current = resetForm;
};

const bindRecalculateFields = recalculateFields => {
bindedRecalculateFields.current = recalculateFields;
}

const buildValidationSchema = formSections => {
const schema = formSections.reduce((obj, item) => {
return Object.assign(
Expand Down Expand Up @@ -175,6 +180,14 @@ function RecordForm({
}
}, [mode.isNew, dataProtectionInitialValues]);

const calculatedFields = forms.flatMap(fs => fs.fields.filter(field => field.calculation?.expression));

useEffect(() => {
if (typeof bindedRecalculateFields.current === "function") {
bindedRecalculateFields.current();
}
})

const handleConfirm = onConfirm => {
onConfirm();
if (incidentFromCase?.size) {
Expand All @@ -189,7 +202,6 @@ function RecordForm({
formikValues.current = values;
};

const calculatedFields = forms.flatMap(fs => fs.fields.filter(field => field.calculation?.expression));

if (!isEmpty(initialValues) && !isEmpty(forms)) {
const validationSchema = buildValidationSchema(forms);
Expand All @@ -215,17 +227,16 @@ function RecordForm({
bindSubmitForm(submitForm);
setFormikValuesForNav(values);

useEffect(() => {
bindRecalculateFields(() => {
if (values) {
calculatedFields.forEach(field => {
const result = parseExpression(field.calculation.expression).evaluate(values);

if (values[field.name] !== result) {
setFieldValue(field.name, result, false);
}
});
}
}, [values]);
});

return (
<FormikForm
Expand Down

0 comments on commit 5dffccc

Please sign in to comment.