TanStackT
TanStack3mo ago
1 reply
faint-white

form.setFieldValue won't rerender a component?

Hello, I am a bit lost here. I am using Calendar and so I thought it would be easier to set its values with form.setFieldValue()

The problem here is that when i set the values the Calendar state won't change?

I am using the custom use AppForm if that has any relation.

Also if I try to see the data with form.state.values I don't see them change also. ReactHookForms had something like form.watch()

const { fieldContext, formContext, useFieldContext, useFormContext } =
  createFormHookContexts();

const { useAppForm } = createFormHook({
  fieldComponents: {
    Input: FormInput,
    Image: FormImageUpload,
    Textarea: FormTextarea,
    Select: FormSelect,
    Checkbox: FormCheckbox,
    Switch: FormSwitch,
  },
  formComponents: {},
  fieldContext,
  formContext,
});

export { useAppForm, useFieldContext, useFormContext };


I can see it console.log() but the state of calendar seems same.

const validFrom = form.state.values.valid_from;
  const validUntil = form.state.values.valid_until;

  const handleDateSelect = (range: DateRange | undefined) => {
    console.log("Selected range:", form.state.values.valid_until);
    const from = range?.from ? startOfDay(range.from) : undefined;
    let to = range?.to ? endOfDay(range.to) : undefined;

    if (from && !to) {
      to = endOfDay(from);
    }

    if (from && to && isSameDay(from, to)) {
      to = endOfDay(from);
    }

    // Update both fields
    form.setFieldValue("valid_from", from?.toISOString());
    form.setFieldValue("valid_until", to ? to.toISOString() : "");
  };

  const selectedRange: DateRange | undefined = React.useMemo(
    () => ({
      from: validFrom ? new Date(validFrom) : undefined,
      to: validUntil ? new Date(validUntil) : undefined,
    }),
    [validFrom, validUntil],
  );


 <Calendar
   mode="range"
   defaultMonth={selectedRange?.from}
   selected={selectedRange}
   onSelect={handleDateSelect}
   numberOfMonths={1}
  />
Was this page helpful?