Skip to content

Instantly share code, notes, and snippets.

@stramel
Created March 31, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stramel/585961a209b65a6078432883ba99a456 to your computer and use it in GitHub Desktop.
Save stramel/585961a209b65a6078432883ba99a456 to your computer and use it in GitHub Desktop.
Creates an array field on your form
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