Repository navigation
Expand file tree
/
Copy pathuseStepFormSubmit.ts
More file actions
52 lines (43 loc) · 1.91 KB
/
Copy pathuseStepFormSubmit.ts
File metadata and controls
52 lines (43 loc) · 1.91 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
import type {FormOnyxKeys, FormOnyxValues} from '@components/Form/types';
import * as FormActions from '@userActions/FormActions';
import type {OnyxFormKey, OnyxFormValuesMapping} from '@src/ONYXKEYS';
import type {SubPageProps} from './useSubPage/types';
type UseStepFormSubmitParams = Pick<SubPageProps, 'onNext'> & {
formId: OnyxFormKey;
fieldIds: ReadonlyArray<string | number | symbol>;
shouldSaveDraft: boolean;
};
/**
* Non-generic implementation so OXC's React Compiler can memoize the hook.
* OXC bails on type params inside hooks ("Unsupported declaration type for hoisting").
*/
function useStepFormSubmitImpl({formId, onNext, fieldIds, shouldSaveDraft}: UseStepFormSubmitParams) {
return (values: Record<string, unknown>) => {
if (shouldSaveDraft) {
const stepValues = fieldIds.reduce<Record<string, unknown>>((acc, key) => {
acc[String(key)] = values[String(key)];
return acc;
}, {});
FormActions.setDraftValues(formId, stepValues);
onNext(stepValues);
return;
}
onNext();
};
}
type UseStepFormSubmitParamsGeneric<T extends keyof OnyxFormValuesMapping> = Pick<SubPageProps, 'onNext'> & {
formId: OnyxFormKey;
fieldIds: Array<FormOnyxKeys<T>>;
shouldSaveDraft: boolean;
};
/**
* Hook for handling submit method in substeps.
* When user is in editing mode, we should save values only when user confirms the change
* @param formId - ID for particular form
* @param onNext - callback
* @param fieldIds - field IDs for particular step
* @param shouldSaveDraft - if we should save draft values
*/
export default function useStepFormSubmit<T extends keyof OnyxFormValuesMapping>({formId, onNext, fieldIds, shouldSaveDraft}: UseStepFormSubmitParamsGeneric<T>) {
return useStepFormSubmitImpl({formId, onNext, fieldIds, shouldSaveDraft}) as (values: FormOnyxValues<T>) => void;
}