use-submit-form.ts
Overview
The use-submit-form.ts file defines a React hook useSubmitForm that facilitates submitting database connection parameters and an optional SQL query to test connectivity to a database. It employs schema validation with Zod to ensure the form data conforms to expected types and constraints. The hook integrates with a custom hook useTestDbConnect (imported from elsewhere in the application) that handles the actual database connectivity test request.
This file is primarily concerned with form data validation and submission logic for database connectivity testing within a React application, abstracting away request handling and loading state management.
Detailed Explanation
Schemas
ExeSQLFormSchema
An object schema defining the expected structure of the core database connection parameters:
Property | Type | Description | Validation |
|---|---|---|---|
| string | Type of the database (e.g., MySQL, PostgreSQL) | Non-empty string |
| string | Database name | Non-empty string |
| string | Username for authentication | Non-empty string |
| string | Database host address | Non-empty string |
| number | Port number for database connection | Number (no explicit range) |
| string | Password for authentication | Non-empty string |
| number | Maximum number of records to fetch/return | Number (no explicit range) |
This schema is a plain object, not a Zod schema instance but used as part of the full form schema.
FormSchema
A Zod object schema combining the optional SQL query string with the database connection schema:
const FormSchema = z.object({
sql: z.string().optional(),
...ExeSQLFormSchema,
});
sql: Optional SQL query string.All other fields are required per
ExeSQLFormSchema.
This schema is used to validate the entire form data before submission.
Function: useSubmitForm
Purpose
Defines a React hook that provides form submission logic specifically for testing database connections using the given form data.
Implementation Details
Uses the
useTestDbConnecthook (from'@/hooks/use-agent-request') to get:testDbConnect: a function to initiate the test connection request.loading: a boolean flag indicating if the test connection request is in progress.
Defines
onSubmitas a memoized callback (withuseCallback) that:Accepts validated form data (
data), typed asz.infer<typeof FormSchema>.Calls
testDbConnect(data)to trigger the connectivity test.
Returns an object containing:
loading: to indicate submission status.onSubmit: the function to be called when the form is submitted.
Parameters
None directly; however
onSubmitaccepts a single argument:data(type inferred fromFormSchema): The validated form data object containing all database connection parameters and optional SQL query.
Return Value
An object:
{
loading: boolean,
onSubmit: (data: z.infer<typeof FormSchema>) => Promise<void>
}
Usage Example
import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { FormSchema, useSubmitForm } from './use-submit-form';
function DatabaseTestForm() {
const { loading, onSubmit } = useSubmitForm();
const { register, handleSubmit } = useForm({
resolver: zodResolver(FormSchema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('db_type')} placeholder="Database Type" />
<input {...register('database')} placeholder="Database Name" />
<input {...register('username')} placeholder="Username" />
<input {...register('host')} placeholder="Host" />
<input type="number" {...register('port', { valueAsNumber: true })} placeholder="Port" />
<input {...register('password')} type="password" placeholder="Password" />
<input type="number" {...register('max_records', { valueAsNumber: true })} placeholder="Max Records" />
<textarea {...register('sql')} placeholder="SQL Query (optional)" />
<button type="submit" disabled={loading}>
{loading ? 'Testing...' : 'Test Connection'}
</button>
</form>
);
}
Important Implementation Details
Schema Validation: By leveraging Zod schemas, this file ensures form data is validated before submission, preventing malformed or incomplete data from reaching the database testing logic.
Hook Dependencies: The
useSubmitFormhook depends on the external hookuseTestDbConnectfor performing the actual connectivity test. This separation of concerns allows the form logic to remain clean and reusable.Optional SQL Query: The form supports an optional SQL query (
sql) allowing the user to test specific queries against the database, not just the connection.Loading State Management: The
loadingflag returned fromuseTestDbConnectis exposed to the consumer ofuseSubmitFormto provide UI feedback during asynchronous operations.
Interaction with Other Parts of the System
useTestDbConnectHook: This imported hook is responsible for executing the database connection test request. It likely interacts with an API or backend service that attempts to connect to the database using the provided credentials and query.Form UI Components: This hook is intended to be used by React components that manage the form UI and user input. It abstracts away submission logic and validation schema details.
Validation Libraries: Uses Zod for schema definitions and validation, ensuring type-safe form data.
React Hooks: Uses
useCallbackto memoize theonSubmithandler for performance optimization.
Mermaid Diagram
This flowchart represents the relationship between the main entities in this file: the schemas, the useTestDbConnect hook, and the useSubmitForm hook that consumes them.
flowchart TD
A[Form Data] -->|Validated by| B[FormSchema (Zod)]
B -->|Validated Data| C[useSubmitForm Hook]
C -->|Calls| D[useTestDbConnect Hook]
D -->|Performs| E[Test DB Connection]
C -->|Exposes| F[onSubmit(data)]
C -->|Exposes| G[loading flag]
style A fill:#f9f,stroke:#333,stroke-width:1px
style B fill:#bbf,stroke:#333,stroke-width:1px
style C fill:#bfb,stroke:#333,stroke-width:1px
style D fill:#fbf,stroke:#333,stroke-width:1px
style E fill:#ffb,stroke:#333,stroke-width:1px
style F fill:#fbf,stroke:#333,stroke-width:1px
style G fill:#fbf,stroke:#333,stroke-width:1px
Summary
File Purpose: Provides form validation schema and a React hook to submit database connection parameters and optionally an SQL query to test connectivity.
Key Exports:
ExeSQLFormSchema: core DB connection schema fragment.FormSchema: full form validation schema.useSubmitForm: React hook exposingonSubmitandloading.
Dependency: Relies on
useTestDbConnectfor backend connectivity testing.Use Case: Simplifies form integration and submission for database connection testing in the UI layer.
This documentation should enable developers to understand the role of this file, how to use the exported hook and schemas, and how it fits into the larger system for database connection testing.