Page updated Mar 6, 2024

Manage form lifecycle

Hook into the form's lifecycle events to customize user input before submission, run validations, or handle errors.

Lifecycle diagram of the Amplify Forms

  1. Initial state - The inputs are either empty or pre-populated based on a default value provided by you.

Use case: If your user clicks on the Clear or Reset button, they'll be brought back to this state.

  1. onChange - Event when form data is changed by the user.

Use case: Use this to get the form data after every user input.

  1. onValidate - Event hook for custom validations. This event triggers after onChange.

Use case: Use this to extend validation rules via code. onValidate also supports asynchronous validation rules, which enable you to validate the form input against external APIs.

  1. onSubmit - Event when your user clicks the Submit button.

Use case: If your form is not connected to a data model, use set this event handler to retrieve the form data. If your form is connected to a data model, use this to customize the provided form data before they are saved to the cloud.

  1. onSuccess - Event when saving form data to the cloud succeeds.

Use case: Use this to dismiss the form or reroute your user after a successful form submission. Only use this if your form is connected to a data model.

  1. onError - Event when saving form data to the cloud fails.

Use case: Use this to log the error and investigate further if your validation rules need to be enhanced to catch input formatting issues. Only use this if your form is connected to a data model.

  1. onCancel - Event when your user clicks on the Cancel button.

Use case: Use this to dismiss the form without saving the form data.

Get form data as your user inputs data - onChange

In some cases, you want to get the form data in real-time as the user is filling the form. The onChange event provides you the form data in the fields parameter. We recommend you to use onChange if you opted to hide all form action buttons (Submit, Cancel, Clear, Reset).

1import { useState } from 'react'
2import { HomeCreateForm } from './ui-components'
3
4function App() {
5 const [formData, setFormData] = useState()
6
7 return (
8 <HomeCreateForm onChange={fields => setFormData(fields)}/>
9 )
10}

Extend validation rules in code - onValidate

With the onValidate event, you can extend the validation rules in code. Learn more about How to add validation rules.

Handle form data submissions - onSubmit

onSubmit should be your default way to handle form submission. It is triggered every time the user clicks on the Submit action button.

If your form is connected to a data model, use the onSubmit hook to customize the form data before they are saved to the cloud. The form data that's returned from the onSubmit handler will be saved to the cloud.

For example, if you want to trim all the string data before saving it:

1<HomeCreateForm
2 onSubmit={(fields) => {
3 const updatedFields = {}
4 Object.keys(fields).forEach(key => {
5 if (typeof fields[key] === 'string') {
6 updatedFields[key] = fields[key].trim()
7 } else {
8 updatedFields[key] = fields[key]
9 }
10 })
11 return updatedFields
12 }}
13/>

If your form is not connected to a data model, use the onSubmit hook to submit the form data and dismiss or reroute the form.

For example, let's assume you have an API /submit-home-data and want to hide the form after submission:

1import { useState } from 'react'
2import { HomeCreateForm } from './ui-components'
3
4function App() {
5 const [showForm, setShowForm] = useState(true)
6
7 return (
8 {showForm &&
9 <HomeCreateForm onSubmit={async (fields) => {
10 const response = await fetch("/submit-home-data", {
11 method: "POST",
12 headers: {
13 "Accept": "application/json",
14 "Content-Type": "application/json"
15 },
16 body: JSON.stringify(fields) // Pass in form data
17 })
18
19 if (response.status === 200) {
20 setShowForm(false) // Hide the form
21 }
22 }}/>}
23 )
24}

Handle form data successfully saving to the cloud - onSuccess

If your form is connected to a data model, use the onSuccess hook to dismiss form after the form data has been successfully submitted.

1import { useState } from 'react'
2import { HomeCreateForm } from './ui-components'
3
4function App() {
5 const [showForm, setShowForm] = useState(true)
6
7 return (
8 {showForm &&
9 <HomeCreateForm onSuccess={() => {
10 setShowForm(false) // Hide the form
11 }}/>}
12 )
13}

Handle form submission errors - onError

If your form is connected to a data model, you might encounter additional errors during the submit process. You can log these errors and present an alert to customers by using the onError handler.

1import { HomeCreateForm } from './ui-components'
2
3function App() {
4 return (
5 <HomeCreateForm onError={(error) => {
6 console.log(error)
7 }}/>
8 )
9}

Handle user clicking on Cancel action button - onCancel

If the user clicks on the Cancel action button, you can use the onCancel event to hide the form or route the customer to another page.

1import { useState } from 'react'
2import { HomeCreateForm } from './ui-components'
3
4function App() {
5 const [showForm, setShowForm] = useState(true)
6
7 return (
8 {showForm &&
9 <HomeCreateForm onCancel={() => {
10 setShowForm(false) // Hide the form
11 }}/>}
12 )
13}