Created
March 31, 2020 17:19
-
-
Save stramel/585961a209b65a6078432883ba99a456 to your computer and use it in GitHub Desktop.
Creates an array field on your form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react' | |
import { useFormContext } from 'react-hook-form' | |
export default function useArrayField<T>({ name, defaultValue = [] }: { name: string; defaultValue?: T[] }) { | |
const { register, setValue, unregister } = useFormContext() | |
const [items, setItems] = useState<T[]>(defaultValue) | |
// Manually register our array field | |
useEffect(() => { | |
register({ name }) | |
return () => { | |
unregister(name) | |
} | |
}, []) | |
// Update the form value on change | |
useEffect(() => { | |
setValue(name, items) | |
}, [items, name, setValue]) | |
return { | |
items, | |
insert(item: T, index: number) { | |
setItems(items => { | |
const tempItems = [...items] | |
tempItems.splice(index, 0, item) | |
return tempItems | |
}) | |
}, | |
remove(index: number) { | |
setItems(items => { | |
const tempItems = [...items] | |
tempItems.splice(index, 1) | |
return tempItems | |
}) | |
}, | |
append(item: T) { | |
setItems(items => [...items, item]) | |
}, | |
prepend(item: T) { | |
setItems(items => [item, ...items]) | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment