TanStackT
TanStack3y ago
15 replies
verbal-lime

Overwriting defaultValues from React Hook Form with data from useQuery

Hello, I am having trouble mixing useQuery from React Query together with React Hook Form
const { data, isLoading } = useQuery<AddEventFormData>(
    ["eventDetails"],
    () => getEventBySlug(id),
    {
      enabled: id.length > 0,
    }
  );

  const eventDetailsToEdit = useMemo(() => {
    if (isLoading) {
      return {};
    }

    return {
      name: data?.name,
      tags: data?.tags,
      timezone: data?.timezone,
      description: data?.description,
      locationType: data?.location.location_type,
      sections: [],
      category: null,
      mainImage: undefined,
      additionalImages: [],
      path: "",
      startTime: undefined,
      endTime: undefined,
      maxTicketsPerOrder: 0,
    };
  }, [data, isLoading]);

  const methods = useForm<AddEventFormData>({
    resolver: zodResolver(eventSchema),
    // mode: "onChange",
    defaultValues: {
      name: "",
      sections: [],
      tags: [],
      timezone: null,
      description: "",
      category: null,
      mainImage: undefined,
      additionalImages: [],
      locationType: "live",
      currency: "",
      path: "",
      startTime: undefined,
      endTime: undefined,
      maxTicketsPerOrder: 0,
      ...eventDetailsToEdit,
    },
  });

The eventDetailsToEdit is supposed to reset the empty values, but I keep getting an error value is undefined in the browser, however, on older tabs I have open on the page, the spread operator does what it's supposed to, I am assuming it's due to cache, however when refreshing the same error pops up
Was this page helpful?