Search code examples
reactjsreact-hook-formtanstackreact-query

Updating react hook form with useQuery and without useEffect?


I'm fetching currentPerson using useQuery to fill a React hook form with currentPerson's data:

// TS

const currentUserId = '1';

const {
  data: currentPerson,
} = useQuery({
  queryKey: ['person', currentUserId],
  queryFn: ({ queryKey }) => {
    const [, id] = queryKey;
    return fetchPerson(id);
  },
});

const form = useForm<z.infer<typeof formSchema>>({
  resolver: zodResolver(formSchema),
  defaultValues: {
    email: currentPerson?.email || '',
    phone: currentPerson?.phone || '',
  },
});

// TSX

<Form {...form}>
  <form>
  </form>
</Form>

The issue is that useForm will run before currentPerson has been fetched, populating the form with empty strings. Is there a way to avoid this? Or using useEffect with currentUser as dependency is the only way to go?


Solution

  • You can simply wait to render the form until the data for the current person is available. This ensures the form is only shown after the necessary data has been fetched. Here is how you can do this:

    // your code
    
    return (
      currentPerson ? (
        <Form {...form}>
          <form>
          </form>
        </Form>
      ) : <div>Loading...</div>
    );