T
TanStack5w ago
ambitious-aqua

deriving field state value from bigger (field state?) objects

hello in my form i'd like to have an intermediate object between what i submit and what i display. Take the use-case of a "user search" input. you'd like to keep the whole user object in the field state to display the user name in the input, although you might want to submit (and validate) the user id only. i could either: 1. have the user object in the defaultValues rather than the userId, but then my onSubmit cannot pass value seamlessly (need to { ...value, userId: value.user.id }) 2. have a separate state for this, which works but is ugly i was wondering if there's a way to store this additional data (in the store maybe) and wire back the "userId" as a getter of sort. thanks !
4 Replies
quickest-silver
quickest-silver5w ago
I usually combine this with useQuery. get the user-object const userQuery = useUser() You could disable the submit button or show a loading indicator until the query is fetched successfully Then in onSubmit you spread in the userQuery.data and the value that comes from your form This way you do not need to have more data in your form&schema as you need your users to provide via the form fields
ambitious-aqua
ambitious-aquaOP5w ago
@ksgn in the case of a search, the input has the data[] already so it'd be wasteful to do another query to get something we already have no? but your way would be following the idea of having separate state
quickest-silver
quickest-silver4w ago
I wanted to build out an example but couldn't find the time. What I wanted to build: the UI would show a Seach-Input and you could type in a username it would search using the github api https://api.github.com/users/$searchQuery the form would only know a searchQuery: string field in onSubmit the whole Object returned from the github-api would be there Does that fit your usecase? Maybe it's something you could make a Stackblitz for and we could discuss from there? https://stackblitz.com/github/tanstack/form/tree/main/examples/react/simple
ambitious-aqua
ambitious-aquaOP2w ago
@ksgn thanks. i actually found a way, although it's not super obvious: 1. in defaultValues, add both fields ({ user, userId: user.id }) 2. in the event handler where you put field.handleChange, instead of newUser => field.handleChange(newUser), add a 2nd call to: form.setFieldValue('userId', newVal.id) this probably the cleanest way i found, although you need to play a little with the types and the schema validator to strip out user and only submit userId in your form. but it works!

Did you find this page helpful?