Skip to content

useForm

Use form model in react component

Type Signature:

ts
interface UseFormProps {
  resetOnUnmount?: boolean;
}

type AnyForm = FormType<any, any, any>;

function useForm<
  T extends AnyForm,
  Schema extends ReadyFieldsGroupSchema = T extends FormType<infer K, any, any>
    ? K
    : never,
  Values extends FormValues<any> = T extends FormType<any, infer K, any>
    ? K
    : never,
  Errors extends FormErrors<any> = T extends FormType<any, any, infer K>
    ? K
    : never,
>(form: T, props?: UseFormProps): ReactForm<Schema, Values, Errors>;

Example Usage:

tsx
import { useForm } from '@effector-reform/react';
import { createForm } from '@effector-reform/core';

const form = createForm({
  schema: {
    name: '',
    age: 18,
  },
});

function Form() {
  const { fields, onSubmit } = useForm(form);

  return (
    <form onSubmit={onSubmit}>
      <input
        value={fields.name.value}
        onChange={(event) => fields.name.onChange(event.currentTarget.value)}
        onBlur={fields.name.onBlur}
        onFocus={fields.name.onFocus}
      />

      <input
        type="number"
        value={fields.age.value}
        onChange={(event) =>
          fields.age.onChange(parseInt(event.currentTarget.value))
        }
        onBlur={fields.age.onBlur}
        onFocus={fields.age.onFocus}
      />

      <button type="submit">Submit</button>
    </form>
  );
}

API

nametypedescription
valuesValuesform values
errorsErrorsform errors (Note: array field error stored in format { error: null, errors: [] })
fieldsReactFields<Schema>form fields (contains object of ReactFields)
snapshotValuescontains last saved snapshot of values (update on every submitted and validated event or by onForceUpdateSnapshot)
isValidbooleanis form valid
isChangedbooleantrue if snapshot not equals to values, false if equal
isValidationPendingbooleanis validating
onSubmit() => voidsubmit form
onValidate() => voidvalidate form
onReset() => voidreset form values
fill(payload: { values?: PartialRecursive<Values>; errors?: ErrorsSchemaPayload; }) => voidset values/errors of form without trigger isDirty (by default triggerIsDirty = false, but you can pass true if you want trigger isDirty)
onClearOuterErrors() => voidclear form outer errors
onClearInnerErrors() => voidclear form inner errors
onForceUpdateSnapshot() => voidforce update of snapshot

Released under the MIT License.