I have some clearable select, and I want to reset the applets
field in state to an empty array.
JavaScript
x
55
55
1
const defaultFormValues = { device: { initialDevice }, applets: [] };
2
const { control, getValues, setValue, reset, handleSubmit } = useForm<CreateDeviceFormData>({
3
mode: "all",
4
reValidateMode: "onChange",
5
defaultValues: defaultFormValues,
6
resolver: yupResolver(validationSchema),
7
});
8
9
const onChangeHandler = React.useCallback(
10
(value: Experience | null) => {
11
if (value) {
12
setValue("applets", getApplets(value));
13
} else {
14
setValue("applets", []);
15
// reset(defaultFormValues);
16
}
17
18
setValue("device.experience_id", value ? value.id : undefined);
19
},
20
[templateSelector, setValue],
21
);
22
23
console.log("current data", getValues(), control);
24
return (
25
<>
26
<SomeAutocompleteComponent control={control} onChange={onChangeHandler} />
27
<SelectAppletsComponent control={control} />
28
</>
29
);
30
31
32
export const SelectAppletsComponent = ({ control, onChange }) => {
33
const applets = useWatch({ control, name: "applets" }) as Applet[];
34
const device = useWatch({ control, name: "device" }) as Device;
35
36
if (!applets.length) {
37
return null;
38
}
39
40
return (
41
<SpanWrapper className="p-col-8">
42
{applets.map((applet) => (
43
<LabelRadio
44
key={applet.id}
45
inputId={applet.applet_type}
46
value={applet.applet_type}
47
label={applet.name}
48
checked={device.applet_type === applet.applet_type}
49
onChange={onChange}
50
/>
51
))}
52
</SpanWrapper>
53
);
54
};
55
the problem is that clearing the selection on UI with setValue("applets", []);
not working for some reason, and I don’t understand why, and how to do it without reset
method, which resets the whole state, not just single property as I understand
Advertisement
Answer
You should always register fields if you want to use them as RHF’s form state.
JavaScript
1
4
1
React.useEffect(() => {
2
register("applets");
3
}, [register]);
4
This fixes an issue.
Update:
Also a new method resetField
is available