Hello! Let's dive into the next step of our form-building journey.
In our last lesson, we successfully implemented client-side validation using React Hook Form and Zod. This ensures that the data a user enters meets our criteria before it even leaves their browser. Now, we'll focus on what happens next: sending that valid data to a server.
This lesson addresses the learning outcome: Manage asynchronous form submissions, including loading and error states. We will transform our submission handler into an asynchronous function that communicates with a server, and crucially, we'll build a user interface that responds intelligently to the different stages of this process. You'll learn how to provide feedback when the form is submitting (loading state) and how to gracefully handle any issues that arise (error state).
1. Thinking in States: The Declarative Approach
Before we write any code, let's establish a mental model. Your experience in software engineering has likely exposed you to state machines, and that's the perfect way to think about a form's lifecycle. Instead of imperatively telling the UI to "show a spinner" or "hide the button," we will declaratively define the different states our component can be in and render the appropriate UI for each state.
The official React documentation has an excellent guide on this very concept. It walks you through identifying the various 'visual states' of a component and modeling them in your code. This will build a strong conceptual foundation for what we're about to implement.
Please read the first three sections: How declarative UI compares to imperative: This will reinforce the core React philosophy. Step 1: Identify your component’s different visual states: Pay close attention to the list of states: 'Empty', 'Typing', 'Submitting', 'Success', and 'Error'. This is our roadmap. Step 2: Determine what triggers those state changes: Note the distinction between human inputs (a click) and computer inputs (a network response arriving). Our focus today is on the latter.
As the article highlights, our form submission process involves these key states:
- Typing (
idle): The initial state where the user can interact with the form. - Submitting (
loading): The transient state after the user clicks "Submit" but before the server has responded. - Success: The state after the server confirms the data was received and processed successfully.
- Error: The state after the server responds with an error, or a network failure occurs.
Our goal is to manage transitions between these states in a clear and predictable way.
2. Basic Implementation: Loading and Error States
Let's start by implementing this logic using a familiar pattern. We'll use an async function for our submission handler and wrap the network request in a try...catch block. We'll use useState to track the loading and error states.
While we'll eventually integrate this with React Hook Form, understanding the raw mechanics is crucial. The logic for handling an async operation is universal in React.
Fetching Data in React - Complete Tutorial
This video from Cosden Solutions provides a clear, practical demonstration of managing loading and error states for a data fetch. Although it uses useEffect to fetch data on component mount, the core logic inside the async function is identical to what we need for a form submission.
Please watch these two segments: Implementing Loading State (06:28 - 09:44): Observe how an isLoading state variable is set to true before the fetch call and false after it completes. This is the fundamental pattern for showing loading indicators. Handling Errors (09:44 - 14:14): Focus on the use of the try...catch block. The try block contains the 'happy path' logic (the fetch call), and the catch block is where the error state is set if anything goes wrong.
Let's adapt this pattern to a hypothetical form submission handler:
import { useState } from 'react';
// This is a placeholder for your actual API call function
const submitToApi = async (data: YourFormDataType) => {
// Simulate a network delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Simulate a server-side validation error
if (data.email.includes('test@test.com')) {
// The server rejects the request. We throw an error that our catch block will handle.
throw new Error("This email address is already in use.");
}
// On success, the promise resolves.
return { success: true };
};
function MyForm() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const data = Object.fromEntries(formData) as YourFormDataType; // Simplified data extraction
// 1. Reset previous errors and set loading state
setError(null);
setIsSubmitting(true);
try {
// 2. Await the API call
await submitToApi(data);
// If the above line doesn't throw, we're in the success state!
// We'll handle this more explicitly later. For now, we just stop loading.
console.log("Submission successful!");
} catch (err) {
// 3. If an error is thrown, capture it
if (err instanceof Error) {
setError(err.message);
} else {
setError("An unknown error occurred.");
}
} finally {
// 4. Always stop loading, regardless of success or failure
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit}>
{/* ... your form inputs ... */}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
</form>
);
}
This works, but as your CS background will appreciate, managing multiple boolean flags (isSubmitting, isSuccess, isError) can lead to logical paradoxes. Can a form be both submitting and have an error? With this model, yes, if you forget to set state in the right order. We can do better.
3. A Robust Model: Discriminated Unions in TypeScript
A more robust and type-safe way to model our mutually exclusive states is with a discriminated union. This is a powerful TypeScript pattern that lets us define a single state object where the value of one property (status) dictates the shape of the rest of the object. This makes "impossible states" unrepresentable in our code.
Loading States and Error Handling in React with TypeScript
This article by Steve Kinney elegantly explains the problem with boolean flags and presents discriminated unions as the superior solution for managing async states in React with TypeScript.
Please read these key sections: The Problem with Boolean Flags: This section articulates the exact issue we just discussed. Discriminated Unions: Making Impossible States Impossible: This is the core of the lesson. Study the TodosState type definition and see how it cleanly separates idle, loading, success, and error states. Notice how you can't access data unless status is 'success'. Best Practices: This provides a concise summary of the principles.
Let's refactor our form's state using this pattern:
// Define our states using a discriminated union
type FormStatus =
| { status: 'idle' }
| { status: 'submitting' }
| { status: 'success' }
| { status: 'error'; error: string };
function MyFormWithDiscriminatedUnion() {
const [formStatus, setFormStatus] = useState<FormStatus>({ status: 'idle' });
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
// ... form data extraction ...
setFormStatus({ status: 'submitting' }); // Transition to submitting state
try {
await submitToApi(data);
setFormStatus({ status: 'success' }); // Transition to success state
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "An unknown error occurred.";
setFormStatus({ status: 'error', error: errorMessage }); // Transition to error state
}
};
// The UI is now driven by a single state object
return (
<form onSubmit={handleSubmit}>
{/*
You can render a success message when the form is in the success state.
We'll cover resetting the form in the next lesson.
*/}
{formStatus.status === 'success' ? (
<p>Thank you for your submission!</p>
) : (
<>
{/* ... your form inputs ... */}
<button type="submit" disabled={formStatus.status === 'submitting'}>
{formStatus.status === 'submitting' ? 'Submitting...' : 'Submit'}
</button>
{formStatus.status === 'error' && (
<p style={{ color: 'red' }}>{formStatus.error}</p>
)}
</>
)}
</form>
);
}
This approach is cleaner, more predictable, and leverages the full power of TypeScript to prevent bugs.
Test your understanding!
In the MyFormWithDiscriminatedUnion example, imagine you want to allow the user to try submitting again after an error. The current UI just shows an error message. How might you change the handleSubmit function and the JSX to allow a retry?
Specifically, if the formStatus is 'error', how could the user transition the form back to the 'idle' or 'submitting' state?
Show answer
When an error occurs, the form state becomes { status: 'error', error: '...' } and the submit button is re-enabled because formStatus.status is no longer 'submitting'.
The user can simply try clicking the "Submit" button again. Our handleSubmit function is designed to handle this perfectly! The first line in the handler is setFormStatus({ status: 'submitting' }), which correctly transitions the component out of the 'error' state and into the 'submitting' state for the new attempt. The catch block will then replace the old error message with a new one if the retry also fails.
No changes are needed; the current implementation already supports retrying! This demonstrates the robustness of a well-defined state machine.
4. Integration with React Hook Form
Now, let's bring this back to the library we've been using. React Hook Form makes managing submission states even easier by providing built-in state for this exact purpose.
When you use handleSubmit from useForm, it's aware of whether the onSubmit function you provide is an async function.
- While your
asyncfunction is pending, React Hook Form automatically setsformState.isSubmittingtotrue. - Once your function resolves or rejects,
formState.isSubmittingbecomesfalse.
This means we get the loading state management for free!
For error handling, especially for server-side validation errors (e.g., "username is taken"), React Hook Form provides a setError function. This lets us programmatically set an error on a specific field, which is excellent for user feedback.
Here is a complete example integrating everything:
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
// Zod schema from the previous lesson
const FormSchema = z.object({
email: z.string().email(),
// ... other fields
});
type FormSchemaType = z.infer<typeof FormSchema>;
// Mock API call that can return specific field errors
const submitWithFieldErrors = async (data: FormSchemaType) => {
await new Promise(resolve => setTimeout(resolve, 1500));
if (data.email.includes('taken@example.com')) {
// This mimics a 400 Bad Request from a server
// with a specific field error.
const error = new Error("This email is already taken.");
(error as any).field = 'email'; // Attach field info to the error
throw error;
}
return { success: true };
};
function MyFinalForm() {
const {
register,
handleSubmit,
setError,
formState: { errors, isSubmitting }
} = useForm<FormSchemaType>({
resolver: zodResolver(FormSchema),
});
const onSubmit = async (data: FormSchemaType) => {
try {
await submitWithFieldErrors(data);
console.log('Success!');
// Here you would typically navigate away or show a success message.
} catch (error) {
if (error instanceof Error && (error as any).field) {
// This is a server-side validation error for a specific field
const field = (error as any).field as keyof FormSchemaType;
setError(field, {
type: 'server',
message: error.message,
});
} else {
// This is a generic network or server error
setError('root.serverError', {
type: 'server',
message: error instanceof Error ? error.message : 'An unknown error occurred',
});
}
}
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('email')} />
{errors.email && <p>{errors.email.message}</p>}
{/* ... other fields ... */}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'}
</button>
{errors.root?.serverError && <p>{errors.root.serverError.message}</p>}
</form>
);
}
In this final pattern, we leverage isSubmitting for the loading state and the setError function to handle both generic errors (root.serverError) and field-specific errors returned from our API. This provides a professional and robust user experience.
Conclusion
You have now mastered a critical part of building interactive web applications. You can confidently handle the entire lifecycle of a form, from client-side validation to asynchronous submission with clear user feedback.
Key Takeaways:
- Think in States: Modeling your form as a state machine (
idle,submitting,success,error) leads to more predictable and maintainable code. - Handle Async with
try/catch: Theasync/awaitsyntax combined with atry...catch...finallyblock is the fundamental pattern for managing asynchronous operations in JavaScript. - Use Discriminated Unions for Type Safety: This TypeScript pattern eliminates "impossible states" and makes your state management more robust.
- Leverage React Hook Form: The library simplifies submission state management with the built-in
formState.isSubmittingflag and the powerfulsetErrorfunction for handling server-side errors.
In our final lesson of this module, we will address the last piece of the puzzle: Reset form state after a successful submission. We'll see how to clear the input fields and return the form to its initial state, ready for another entry.