useCollection()

useCollection

Provides functionality for managing and manipulating repeatable form fields within a form context.

Collection Props

name

Required

Name of the fields collection

connect

Allows you to connect your collection to a form.

defaultValue

Allows you to pass defaultValue to the collection, that will be apply if there is no initialValues. That defaultValue overrides collection fields default values.

Collection Values

keys

Array of autogenerated keys for each collection item.

length

Number of items in the collection.

insert(index, data, options)

Allows to add an item at specified index.

options are the same as for form.setValues options

insertMultiple(index, data, options)

Allows to add a list of items at specified index.

options are the same as for form.setValues options

append(data, options)

Allows to add an item at the end of the collection.

options are the same as for form.setValues options

prepend(data, options)

Allows to add an item at the begin of the collection.

options are the same as for form.setValues options

remove(index)

Allows to remove an item at specified index.

⚠️

There is no keepPristine option on this function, because currently there is an issue caused by the fact removed item doesn't have pristine state

removeMultiple(indexes)

Allows to remove multiple items at specified indexes.

⚠️

There is no keepPristine option on this function, because currently there is an issue caused by the fact removed item doesn't have pristine state

set(collection, options)

Allows to change the value of all the collection.

options are the same as for form.setValues options

setKeys(keys)

Allows to update collection keys values.

// Case with collection defined in a form context
const collection = useCollection("members");
 
{
  collection.keys.map((key, index) => (
    <div key={key}>
      <MyField name={`members[${index}].name`} />
    </div>
  ));
}
 
// Case with collection and form defined at same level
const form = useForm();
const collection = useCollection("members", {
  connect: form,
});
 
{
  collection.keys.map((key, index) => (
    <div key={key}>
      <MyField name={`members[${index}].name`} />
    </div>
  ));
}

See example ↗ (opens in a new tab)