View on GitHub

React Hook Form Plus

(RHF+)

Form metadata

Purpose

This feature adds a new metadata property to the Form state to store custom metadata related to form right inside the form object.

Benefits

API Changes

Property updates

type MetadataValue =
  | string
  | number
  | boolean
  | null
  | MetadataValue[]
  | { [key: string]: MetadataValue };

export type FormMetadata = { [key: string]: MetadataValue };

// when user as a generic type parameter
<TMetadata extends FormMetadata = any>
export type UseFormProps<...> = Partial<{
    // ... existing properties
    defaultMetadata: FormMetadata; // New property
}>;
export type UseFormReturn<...> = {
    // ... existing properties
    setMetadata: UseFormSetMetadata<TMetadata>; // New method
    updateMetadata: UseFormUpdateMetadata<TMetadata>; // New method
};
export type FormState<TFieldValues extends FieldValues = FieldValues> = {
  // ... existing properties
  metadata: TMetadata; // New property
};

Description

To properly use the new form metadata, you first pass an object value with the desired type to the defaultMetadata. This will initiate the metadata when the form is created and define the metadata type for the state and mutation methods. The metadata object can have as many properties as necessary, have nested properties, and valid values include strings, numbers, booleans, nulls, arrays, and objects.

Behavior

You can access the metadata by using the metadata property of formState, which contains the current metadata for the form. The metadata can be updated using the setMetadata and updateMetadata mutation methods.

The setMetadata method replaces the entire metadata object with the new metadata. The updateMetadata method merges the new metadata with the existing metadata. These methods provide flexibility in managing the form metadata, allowing you to either completely replace or partially update the metadata as needed.

Examples

import { useForm } from '@bombillazo/rhf-plus';

const defaultMetadata: {
  id: number;
  name: string;
  is_admin: boolean;
} = {
  id: 1,
  name: 'Bob',
  is_admin: true,
};

function App() {
  const { formState, setMetadata } = useForm({ defaultMetadata });

  return (
    <>
      <form>
        <pre>{JSON.stringify(formState.metadata)}</pre>
      </form>
      <Button onClick={() => {
        setMetadata({ id: 100, name: 'Alice', is_admin: false });
        }}
      >Set Metadata</Button>
    </>
  );
}

Limitations

Backward Compatibility

This feature is fully backward compatible. The metadata functionality is optional and doesn’t affect existing forms that don’t use it.