BearStudio/formiz

Can't access form.values

KannarFr opened this issue · 2 comments

Describe the bug
Using

const form = useForm({ subscribe: 'form' });

Based on Steppers example, form.values is undefined, is that expected behavior? Shouldn't it be accessible for validations as password confirmation?

Maybe it's all about me and another JS issue because I'm quite bad at it :D.

@KannarFr Yes subscribing to the "form" only will not give you access to the "fields" values.
This is for performance optimisation. But you can access the values later in the tree.
This is to prevent the root component to rerender on every field change.

Example:

const MyFormPart = () => {
  const form = useForm(); // same as useForm({ subscribe: true })
  // Have access to form.values
  // Will rerender every time a value change
  return <pre>{JSON.stringify(form?.values, null, 2)}</pre>;
};

const MyFormPart2 = () => {
  const form = useForm({ subscribe: { form: true, fields: ['email', 'password'] } });
  // Have ONLY access to form.values.email and form.values.password
  // Will rerender every time the email or password change
  return <pre>{JSON.stringify(form?.values, null, 2)}</pre>;
};

const MyForm = () => {
  const form = useForm({ subscribe: 'form' });
  // Don't have access to form.values
  // Will NOT rerender every time a value change
  return (
    <Formiz connect={form}>
      <form noValidate onSubmit={form.submit}>
        <Field name="firstName" />
        <Field name="lastName" />
        <Field name="email" />
        <Field name="password" />
        <MyFormPart />
        <MyFormPart2 />
      </form>
    </Formiz>
  );
};

@ivan-dalmet Oh ok, thanks!