hooks.ts


Overview

The hooks.ts file defines a custom React hook, useValidateSubmittable, which integrates with Ant Design's form system to provide real-time validation status of a form. This hook manages form state and validation, allowing components to easily determine whether a form is currently valid and can be submitted.

This utility is particularly useful in React applications using Ant Design's form components, where instant feedback on form validity is required to enable or disable submission buttons or trigger other UI changes.


Exports

useValidateSubmittable

A custom React hook that creates and manages an Ant Design form instance with automatic validation tracking.

Purpose

Usage

import React from 'react';
import { Button, Input } from 'antd';
import { useValidateSubmittable } from './hooks';

const MyFormComponent = () => {
  const { form, submittable } = useValidateSubmittable();

  const onFinish = (values: any) => {
    console.log('Submitted values:', values);
  };

  return (
    <Form form={form} onFinish={onFinish}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: 'Please input your username!' }]}
      >
        <Input placeholder="Username" />
      </Form.Item>
      <Button type="primary" htmlType="submit" disabled={!submittable}>
        Submit
      </Button>
    </Form>
  );
};

Parameters

Returns

An object containing:

Property

Type

Description

form

FormInstance (from Ant Design)

The Ant Design form instance to be attached to <Form>.

submittable

boolean

Indicates whether the form is currently valid and submittable.


Implementation Details

This approach ensures that the submittable state is always synchronized with the current validity of the form fields, updating reactively whenever any form value changes.


Interaction with Other Parts of the System


Mermaid Diagram

flowchart TD
    A[useValidateSubmittable Hook] --> B[Form.useForm()]
    A --> C[useState(submittable)]
    A --> D[Form.useWatch([], form)]
    D --> E[Watched form values]
    A --> F[useEffect]
    F --> G[form.validateFields({ validateOnly: true })]
    G -->|Success| H[setSubmittable(true)]
    G -->|Failure| I[setSubmittable(false)]
    A --> J{Return Object}
    J --> K[submittable]
    J --> L[form]

Summary

hooks.ts provides a clean, reusable hook useValidateSubmittable to integrate Ant Design's form validation status into React components. It simplifies the common pattern of enabling/disabling form submission based on validation without scattering validation logic throughout UI components. This leads to better separation of concerns and cleaner component code.


If you have any questions or need further details on how to extend or customize this hook, feel free to ask!