Replies: 1 comment
|
You don't need function CustomerForm() {
const queryClient = useQueryClient()
const form = useForm({
defaultValues: { postalCode: '', street: '', city: '' },
})
return (
<form>
<form.Field
name="postalCode"
listeners={{
onChangeDebounceMs: 400,
onChange: async ({ value, fieldApi }) => {
const code = value.replace(/\D/g, '')
if (code.length !== 8) return
const address = await queryClient.fetchQuery({
queryKey: ['address', code],
queryFn: () => fetchAddress(code),
staleTime: Infinity,
})
if (!address) return
// the user may have changed the postal code while the request was running
if (fieldApi.state.value.replace(/\D/g, '') !== code) return
fieldApi.form.setFieldValue('street', address.street)
fieldApi.form.setFieldValue('city', address.city)
},
}}
>
{(field) => (
<input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />
)}
</form.Field>
<form.Field name="street">
{(field) => (
<input value={field.state.value} onChange={(e) => field.handleChange(e.target.value)} />
)}
</form.Field>
{/* city… */}
</form>
)
}The listener only runs when the postal code changes, so the address fields stay editable after the autofill. I checked this with
Docs: Listeners. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
The scenario:
I have a customer form with address fields, including a postal code using tanstack forms.
When the user types the postal auto code, I can trigger an API query, using tanstack query, and have that result autofill the rest of the address fields (when applicable).
The only way I can think of is using useEffect, but I think this looks wrong.
All reactions