Need a way to retrieve the new field after useFieldArray's `update`
See original GitHub issueIs your feature request related to a problem? Please describe.
Hi, I’m trying to make an editor for updating fields in an array and the approach is to maintain an editingField
that references the selected field, and pass it to the editor (a subform) as default value, looking like this:
const [editingField, setEditingField] = React.useState();
<Edit
value={editingField}
onSubmit={(data) => {
const index = fields.findIndex((f) => f.id === editingField.id);
if (index !== -1) {
update(index, data);
setEditingField(data);
}
}}
/>
The problem is, data’s ID will be changed when it is put into the array by update
, so I can’t use its ID to find the corresponding field next time I want to update it.
I also created a repro: https://codesandbox.io/s/usefieldarray-with-preview-forked-n1tjyf?file=/src/App.js
Just click on one of the item A/B/C, then click Save twice and it’ll fail.
Describe the solution you’d like
I need a way to retrieve the new field. It can probably be the return value of update
:
const newField = update(index, data);
If that doesn’t make sense, maybe a callback that provides the new field:
update(index, data, (newField) => {
// ...
});
Or, at least provide the new ID:
update(index, data, (newID) => {
const newField = fields.find((f) => f.id === newID);
})
Additional context I know that I can work around this by saving the editing field’s index instead of the field itself, but in my real use case fields are draggable and can be moved among different arrays, meaning that indices can change anytime and therefore maintaining the active index can be very difficult.
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
@guansss : It’s little bit weird when working with field array but the data has no unique identifier itself (not generated ID from react-hook-form). In your use case, just add a unique identifier related to your data which is not updated over changes on field array will solve the issue.
For example:
Please note that useFieldArray already supports “keyName” option change auto-generated identifier of react-hook-form from default name “id” to another name so it won’t affect default identifier name of your data.
Referrer: https://react-hook-form.com/api/usefieldarray
Working demo: https://codesandbox.io/s/usefieldarray-with-preview-forked-089o85?file=/src/App.js
@bluebill1049 I guess I was already doing that,
editingField
is (supposed to be) the hosted state, but the problem is that I can’t correctly get the updated field and assign it toeditingField
.@leapful Thank you, this is a nice solution. But considering useFieldArray already provides such IDs, it would be great if they could be reused so that I don’t have to do it myself - generating and attaching IDs at the beginning and stripping them away at the end.