Get index of pushed value in field array
Is there a way to get access to the index of a field that was pushed to a field array? It doesn't look like anything is returned from the
pushValue()
method. For context, I have an add/edit modal that renders an item in the modal that I am either adding or editing, and that is determined by the index in the array. This is fine with selecting an item to edit because the index was already defined, but when adding I would have to do something like setSelectedIndex(form.state.values.items?.length - 1)
which feels like could lead to edge cases since there's no guarantee the item was pushed before setting that index, right?2 Replies
dependent-tan•8mo ago
Why don’t you just use the index of the array.map that you’re using to render the component?
Perhaps you can give us a code example of what you’re trying to do. I’m struggling to understand why you need the index, if you’re using the array component with the subfield handlers. 🙂
rival-blackOP•8mo ago
@nneaowwplane I am using the index of the
array.map()
for rendering each item in the list, but the selectedIndex
is used to render a a specific item's details in a modal. When I am adding a new item to my list, it doesn't currently have an index so I cant rely on the index to be the one selected to present the modal to "edit" the new item.
Here is my form file in question: https://github.com/tylerpashigian/t3-recipe-book/blob/feature/service-layer-refactor/src/components/recipe/recipe-form.tsx#L384. You can see I am passing in the index, but I have a single shared popover component (basically just a modal on desktop, drawer on mobile) so I need to pass in a singular index, I didnt want to render a separate popover for each ingredient item. Let me know if you have questions and thanks for the reponse!