8000 Resetting a field (or a form) doesn't emit an event · Issue #1570 · TanStack/form · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
Resetting a field (or a form) doesn't emit an event #1570
Open
@luixo

Description

@luixo

Hello,
I have a form with a value I sync with my search param.
To make it sync on mount (search param -> form), I use onMount listener of the field.
To make it sync back later (form -> search param), I intend to use onChange for every field change.

But I figured out that clearing a field doesn't actually emit any event I can listen to.
I ended up moving search param reset function to the place where reset actually happens, but I believe the "reset" event might be a thing to have.

My example (simplified):

const formSchema = z.object({
  userId: z.string(),
    // other values
});

type Form = z.infer<typeof formSchema>;

const Component = () => {
  const [searchParamUserId, setSearchParamUserId] = useSearchParam("userId");
  
  const defaultValues: Partial<Form> = {
    userId: undefined,
  };
  
  const form = useAppForm({
    defaultValues: defaultValues as Form,
    validators: {
      onMount: formSchema,
      onChange: formSchema,
      onSubmit: formSchema,
    },
  });
  
  return (
    <form.AppField
      name="userId"
      listeners={{
        onMount: ({ fieldApi }) => {
          if (userId) {
            fieldApi.setValue(searchParamUserId);
          }
        },
        onChange: ({ value }) => setSearchParamUserId(value),
      }}
    >
      {(field) => (
        <UsersSelect
          selected={field.state.value}
          onSelect={(nextUserId) => {
            // Clicking on the same user should reset value to undefined
            if (nextUserId === field.state.value) {
              form.resetField("userId");
              // Unfortunately, resetting field doesn't emit a listener event
              setSearchParamUserId(undefined);
            } else {
              field.setValue(nextUserId);
            }
          }}
        />
      )}
    </form.AppField>
  );
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0