TanStackT
TanStack8mo ago
58 replies
spotty-amber

Removing an entry from an array causes the array to receive invalid data

Hi there, I have some role management code where I iterate through an array of roles from the backend and show checkboxes for each role and each role is linked to an index in a form array. Whenever I uncheck a checkbox it seems to correctly call form.removeValue (with the correct index) but then when I check the form.state.values.roles there is a weird entry of whatever the last entry of the initial array was but now with just the name property of the whole Role object, which in turn causes my zod validation to fail.

I have a stackblitz where this odd behaviour can be reproduced: https://stackblitz.com/edit/tanstack-form-9vub96pu?file=src%2Findex.tsx

Assuming when I'm editing the user which has both Admin and User:
1. I click Admin to remove it
1. In the breakpoint I have on the
onChange
I correctly see that event.target.checked is false and the else branch is executed
1. When logging form.state.values at this point I see the correct data
1. It correctly finds the
id
of the role to remove
1. field.removeValue(roleIdx) seems to be called with the correct value
1. The form state now results in
{ "name": "John Doe", "age": 30, "roles": [ { "name": "User", "external": false }, { "name": "User" } ] }

1. Click the Submit button
This then trips up Zod which says that roles[1].external is required.

What I find particularly notable is that as far as I can tell this problem is only happening when editing an existing user, but when I log the whole form.state.values as soon as the form loads with the existing data that looks a-ok.

So the question is, why is that second entry in the array even there? What is adding it? Especially since it's not even the role I just clicked to remove.
StackBlitzJeroen Claassens
Run official live example code for Form Array, created by Tanstack on StackBlitz
Form Array Example (duplicated) - StackBlitz
Was this page helpful?