useRBoxForm
useRBoxForm
is a React hook that simplifies form state management by combining the power of RBox
with validation, error handling, and utility functions. It is ideal for building reactive and type-safe forms in React applications.
The useRBoxForm
hook allows you to manage form state reactively, validate inputs, and handle errors with ease. It leverages F-Box’s RBox
abstraction to ensure that all form-related states are synchronized and reactive.
Key Features
- Reactive Form State: Automatically synchronize form fields and validation state.
- Built-in Validation: Simplify input validation with flexible rules.
- Error Rendering: Dynamically render error messages for invalid fields.
- Async Submission Handling: Track the pending state of asynchronous submissions with
isPending
. - Type Safety: Provides strong TypeScript support for predictable development.
Creating a useRBoxForm
Hook
To use useRBoxForm
, pass initial form values and a validation function that defines validation rules for each field.
Example
Supported Patterns
Validating and Rendering Errors
Use the validate
function to define rules for each field. Use renderErrorMessages
to dynamically display error messages.
Async Submission with isPending
The isPending
property indicates whether an asynchronous operation is in progress. You can use it to disable buttons or show loading indicators during submission.
Resetting and Marking Fields
resetForm
: Resets the form to its initial state.markAllEdited
: Marks all fields as edited.
API Methods
useRBoxForm
useRBoxForm<T>(initialValues: T, validate: (form: T) => Validation<T>): UseRBoxFormResult<T>
Creates a reactive form state with validation rules and tracks async submission state.
Parameters
initialValues
:- An object defining the initial values for the form fields.
validate
:- A function returning validation rules as an object where each key is a field name, and the value is an array of validation functions.
Returns
form
:- The current form state.
isPending
:- A boolean indicating whether an asynchronous submission is in progress.
handleChange
:- Updates the value of a specific field and marks it as edited.
handleValidatedSubmit
:- Handles form submission with validation.
renderErrorMessages
:- Dynamically renders error messages for a specific field.
resetForm
:- Resets the form to its initial state.
markAllEdited
:- Marks all fields as edited.
Why Use useRBoxForm
?
With the addition of isPending
, useRBoxForm
now handles both reactive state management and async submission handling. It simplifies form handling in React applications while maintaining clean, type-safe, and maintainable code.
Next Steps
Explore related topics to deepen your understanding:
- RBox API Reference: Learn about the
RBox
abstraction in F-Box. - useBox Reference: Understand how to work with static values in React using
useBox
. - useRBox Guide: Dive into advanced usage patterns for
useRBox
.