From 91979ce232d6b5619ceb814146173df5a22eca07 Mon Sep 17 00:00:00 2001 From: Avram Walden Date: Mon, 29 Apr 2024 09:28:29 -0700 Subject: [PATCH] feat(usedynamicinputs): adds override option to addInput * feat(usedynamicinputs): adds override option to addInput Allows dynamically setting form data values for nested data * feat: updates types --- src/useDynamicInputs.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/useDynamicInputs.ts b/src/useDynamicInputs.ts index 71cdc7b..039c4c2 100644 --- a/src/useDynamicInputs.ts +++ b/src/useDynamicInputs.ts @@ -2,20 +2,19 @@ import { useCallback } from 'react' import { useForm, useFormMeta } from './Form' import { get, set } from 'lodash' import { useNestedAttribute } from './NestedFields' -import { NestedObject } from './useInertiaForm' -export interface DynamicInputsProps { +export interface DynamicInputsProps> { model?: string emptyData: T } -type DynamicInputsReturn = { - addInput: () => void +type DynamicInputsReturn> = { + addInput: (override?: (records: T[]) => Partial | T) => void removeInput: (i: number) => T paths: string[] } -const useDynamicInputs = ({ model, emptyData }: DynamicInputsProps): DynamicInputsReturn => { +const useDynamicInputs = >({ model, emptyData }: DynamicInputsProps): DynamicInputsReturn => { const { setData, unsetData, getData } = useForm() const { model: formModel } = useFormMeta() let inputModel = formModel ?? '' @@ -27,17 +26,22 @@ const useDynamicInputs = ({ model, emptyData }: DynamicI inputModel = `${inputModel}.${model || ''}` - const handleAddInputs = useCallback(() => { - setData((formData: NestedObject) => { + const handleAddInputs = useCallback((override?: (records: T[]) => Partial) => { + setData((formData: Record) => { const clone = structuredClone(formData) - let node: unknown[] = get(clone, inputModel) as unknown[] + let node = get(clone, inputModel) as T[] if(!node || !Array.isArray(node)) { set(clone, inputModel, []) - node = get(clone, inputModel) as unknown[] + node = get(clone, inputModel) as T[] } - node.push(emptyData) + let merge = {} + if(override instanceof Function) { + merge = override(node) + } + + node.push(Object.assign(emptyData, merge)) set(clone, inputModel, node) return clone