Skip to content

Commit

Permalink
Allow fields to be removed manually via removeFields() in useFormContext
Browse files Browse the repository at this point in the history
  • Loading branch information
nikhilag committed Aug 16, 2022
1 parent 4e7e48e commit 3950bfb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/FormProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
IFormContextFieldInput,
IIsDirtyProps,
InitialValues,
IRemoveFieldParams,
} from './types';
import {
getPathInObj,
Expand Down Expand Up @@ -381,7 +382,34 @@ export function useFormContext() {
[formId]
);

return { getValue, setValue, getValues, checkIsDirty };
const removeFields = useRecoilCallback<any, any>(
({ reset }) =>
(params: IRemoveFieldParams) => {
for (const fieldName of params.fieldNames) {
if (typeof fieldName === 'string') {
reset(
fieldAtomFamily({
ancestors: [],
formId,
name: fieldName,
type: 'field',
})
);
} else {
reset(
fieldAtomFamily({
ancestors: fieldName.ancestors ?? [],
formId,
name: fieldName.name,
type: 'field',
})
);
}
}
}
);

return { getValue, setValue, getValues, checkIsDirty, removeFields };
}

export function useFieldArray(props: IFieldArrayProps) {
Expand Down
7 changes: 7 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ export interface FinalValues {
extraInfos: any;
}

export interface IRemoveFieldParams {
fieldNames: (
| string
| { ancestors?: { name: string; rowId: number }[]; name: string }
)[];
}

export interface IFieldWatchParams {
fieldNames: (
| string
Expand Down

0 comments on commit 3950bfb

Please sign in to comment.