Skip to content

Commit

Permalink
Add option to prevent automatic pruning of refless fields
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickDeVries committed May 15, 2024
1 parent 2e474c1 commit 078e162
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
8 changes: 8 additions & 0 deletions src/hooks/UseForm/useForm/types/public.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,13 @@ export interface RegisterOptions<
* @type {?CoordinatesOrNever<TDimensions, CoordinatesOfLength<TDimensions>>}
*/
coordinates?: CoordinatesOrNever<TDimensions, CoordinatesOfLength<TDimensions>>

/**
* If `true`, the field will not be automatically removed when its `ref` is unset
*
* @type {?boolean}
*/
shouldNotBeAutoPruned?: boolean
}

/**
Expand Down Expand Up @@ -309,6 +316,7 @@ export type Fields<
export interface UseFormOptions<TDimensions extends number = 0> {
dimensions?: TDimensions
isRequiredErrorMessageOverride?: string
shouldNotAutoPruneFields?: boolean
}

/**
Expand Down
11 changes: 8 additions & 3 deletions src/hooks/UseForm/useForm/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {
const useForm: UseForm = <TData extends FieldsData, TDimensions extends number = 0>({
dimensions = 0 as TDimensions,
isRequiredErrorMessageOverride,
shouldNotAutoPruneFields = false,
}: UseFormOptions<TDimensions> = {}): UseFormReturn<TData, TDimensions> => {
const fieldsGraph = useRef<FormData<Fields<TData, TDimensions>, TDimensions>>(
new Graph<Fields<TData, TDimensions>, TDimensions>({ dimensions }),
Expand Down Expand Up @@ -163,7 +164,9 @@ const useForm: UseForm = <TData extends FieldsData, TDimensions extends number =
const newFields = Object.keys(fields).reduce(
(acc, fieldName) => ({
...acc,
...(fields[fieldName]?.ref?.current ? { [fieldName]: fields[fieldName] } : {}),
...(fields[fieldName]?.ref?.current || fields[fieldName]?.options?.shouldNotBeAutoPruned
? { [fieldName]: fields[fieldName] }
: {}),
}),
{},
)
Expand Down Expand Up @@ -317,7 +320,9 @@ const useForm: UseForm = <TData extends FieldsData, TDimensions extends number =
onSubmit,
onError,
}: HandleSubmitOptions<TData, TDimensions, TShouldSkipValidations>) => {
unregisterInactiveFields()
if (!shouldNotAutoPruneFields) {
unregisterInactiveFields()
}

if (shouldSkipValidations) {
const typedData = getTypedData(fieldsGraph.current)
Expand Down Expand Up @@ -349,7 +354,7 @@ const useForm: UseForm = <TData extends FieldsData, TDimensions extends number =
}
}
},
[resetChanged, unregisterInactiveFields, updateErrors],
[resetChanged, shouldNotAutoPruneFields, unregisterInactiveFields, updateErrors],
)

const register: Register<TData, TDimensions> = useCallback(
Expand Down

0 comments on commit 078e162

Please sign in to comment.