Blog>
Snippets

Handling Server-side Errors in Form Submissions

Explains capturing and displaying server-side error feedback in the form UI, leveraging React's state management for error display.
const [errorMessage, setErrorMessage] = useState('');
Initializing a state variable 'errorMessage' to store the server-side error message.
const handleSubmit = async (event) => {
  event.preventDefault();
  // Reset error message at the start of submission
  setErrorMessage('');
  try {
    // Perform form submission logic here, e.g., using axios or fetch
    // const response = await axios.post('/api/form-submit', formData);
    // Process successful submission (not shown here)
  } catch (error) {
    // Capture server-side error
    if (error.response && error.response.status >= 400 && error.response.status < 500) {
      // Update state with the error message to display it
      setErrorMessage(error.response.data.message);
    } else {
      // Handle other errors differently (not shown here)
      console.error('An unexpected error occurred:', error);
    }
  }
};
The handleSubmit function prevents the default form submission behavior, resets the error message, tries to submit the form data, catches errors, checks if it's a server-side error (status 400-499), and updates the error message state with the received error message.
// In the component's return statement
<form onSubmit={handleSubmit}>
  {errorMessage && <div>{errorMessage}</div>}
  // Form fields here
  <button type="submit">Submit</button>
</form>
Rendering the form with an onSubmit handler set to our handleSubmit function. If there's an errorMessage, it gets displayed above the form fields.