useCollection
Provides functionality for managing and manipulating repeatable form fields within a form context.
Since version 2.3.0, a collection manages its own pristine state. This means that when you trigger an action on a collection (without using the keepPristine option), the collection's pristine state is updated to false, and the form's pristine state also becomes false.
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, options)
Allows to remove an item at specified index.
options
are the same as for form.setValues options
removeMultiple(indexes, options)
Allows to remove multiple items at specified indexes.
options
are the same as for form.setValues options
set(collection, options)
Allows to change the value of all the collection.
options
are the same as for form.setValues options
setKeys(keys, options)
Allows to update collection keys values.
options
are the same as for form.setValues options
// 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>
));
}