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

🪟 🐛 Update <ConditionSection /> to update values after form validation is updated #14802

Closed
wants to merge 3 commits into from
Closed
Changes from 2 commits
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
@@ -1,5 +1,5 @@
import { useFormikContext, setIn } from "formik";
import React, { useCallback, useMemo } from "react";
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import styled from "styled-components";

import { Label, DropDown } from "components";
Expand Down Expand Up @@ -37,7 +37,8 @@ interface ConditionSectionProps {
*/
export const ConditionSection: React.FC<ConditionSectionProps> = ({ formField, path, disabled }) => {
const { widgetsInfo, setUiWidgetsInfo } = useServiceForm();
const { values, setValues } = useFormikContext<ServiceFormValues>();
const { values, setValues, validateForm } = useFormikContext<ServiceFormValues>();
const shouldValidateRef = useRef<boolean>(false);

const currentlySelectedCondition = widgetsInfo[formField.path]?.selectedItem;

Expand All @@ -56,12 +57,15 @@ export const ConditionSection: React.FC<ConditionSectionProps> = ({ formField, p
)
: values;

// Wait until the form state updates to run validation with the updated schema
shouldValidateRef.current = true;

setValues(newValues, false);
setUiWidgetsInfo(formField.path, {
selectedItem: selectedItem.value,
});
setValues(newValues);
},
[values, formField.conditions, setValues, setUiWidgetsInfo, formField.path]
[formField.conditions, formField.path, values, setValues, setUiWidgetsInfo]
);

const options = useMemo(
Expand All @@ -72,7 +76,16 @@ export const ConditionSection: React.FC<ConditionSectionProps> = ({ formField, p
})),
[formField.conditions]
);

useEffect(() => {
if (shouldValidateRef.current) {
validateForm();
shouldValidateRef.current = false;
}
}, [validateForm, widgetsInfo]);

const label = formField.title || formField.fieldKey;
const blocks = formField.conditions[currentlySelectedCondition];

return (
<GroupControls
Expand All @@ -92,12 +105,7 @@ export const ConditionSection: React.FC<ConditionSectionProps> = ({ formField, p
}
>
<ConditionControls>
<FormSection
blocks={formField.conditions[currentlySelectedCondition]}
path={path}
disabled={disabled}
skipAppend
/>
<FormSection blocks={blocks} path={path} disabled={disabled} skipAppend />
</ConditionControls>
</GroupControls>
);
Expand Down