-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathuseConfigurationForm.tsx
More file actions
74 lines (66 loc) · 2.54 KB
/
useConfigurationForm.tsx
File metadata and controls
74 lines (66 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
import { useEffect, useMemo } from 'react';
import type { InputsType } from '~/routes/configuration';
import { useForm, type KeepStateOptions, type SubmitHandler } from 'react-hook-form';
import { getDefaultValuesFromConfigObject } from '~/components/form/utils/getDefaultValuesFromConfigObject';
import { convertFormValuesToConfigObject } from '~/components/form/utils/convertFormValuesToConfigObject';
import { useLocation } from 'react-router';
import type { FormValue, Restrictions } from '~/components/form/types';
import { useConfigurationMutation } from '~/api/mutations/useConfigurationMutation';
const RESET_PROPS: KeepStateOptions = { keepDirty: false };
/**
* useConfigurationForm hook
* Provides form state management to child components.
* @param {object} options - The options for the form.
* @param {FormItem | undefined} options.configuration - The configuration object.
* @param {string} options.configurationName - The name of the configuration.
* @returns {FormContextValue} Form context value
*/
export const useConfigurationForm = ({
configuration,
configurationName,
configurationRestrictions,
}: {
configuration: FormValue | undefined;
configurationName: string;
configurationRestrictions: Restrictions | undefined;
}) => {
const { pathname } = useLocation();
const mutation = useConfigurationMutation(configurationName);
const defaultValues = useMemo(
() => getDefaultValuesFromConfigObject(configuration, pathname),
[configuration, pathname],
);
const { control, handleSubmit, getValues, formState, reset } = useForm<InputsType>({
defaultValues,
});
const onSubmit: SubmitHandler<InputsType> = (data) => {
const configurationData = convertFormValuesToConfigObject(
data,
configurationRestrictions,
pathname,
);
mutation.mutate(configurationData);
};
useEffect(() => reset(defaultValues, RESET_PROPS), [defaultValues, reset]);
return {
control,
handleSubmit,
getValues,
formState,
reset,
onSubmit,
};
};