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