The useActionData
hook is a route action React hook, which provides a mechanism to manipulate data using plain HTML and HTTP. The complexity pertaining to asynchronous UI and validation is abstracted away by the React Router. This hook returns a value from either the data from the previous navigation’s action
result or undefined
if no submission was made. Data can be submitted through various methods like post, put, or patch. This hook is useful during form validation: it can raise an error if the form isn’t correctly filled and prompt the user to try again.
The following code snippet shows how to use the useActionData
hook in any component (it’s used in a way similar to other React hooks):
import { useActiondata } from "react-router-dom";function my_favourite_place_component(){const form_action_data = useActionData();}
useActionData
hookIn the coming section, we’ll see the use cases of useActionData
.
useActionData
for form input validationReact provides a number of ways to perform form input validation. In React, input validation is possible through the useFormContext
hook’s register
function. However, we’ll see how to do this in the coming sections with the useActionData
hook. It allows us to access our submitted form data and corresponding errors inside a component. Before user-entered data can be further manipulated, we must ensure that the input data is correct and valid. For validation purposes, we can add multiple constraints on the data. For example, an employee’s age should not exceed a hundred years could be a constraint. This way, useActiondata
hook provides server-side input validation.
After the form is submitted, the useActionData
hook can redirect the user to another page. For example, after form submission, we might want the user to return to the home page. For this purpose, we’ll include a redirect("/home_page_path")
statement at the end of our action function. This way, not only is a user’s data validated, but the user can return to other activities on the home page at the end of the form submission.
Let’s look at a more widely used use case of the useActionData
hook, form input validation.
The following example demonstrates how to perform form input validation using the useActionData
hook. It contains two components:
EducativeForm()
: It renders a form for entering employee details and displays any errors.
EducativeFormAction()
: It handles form submissions, validates input, and returns errors, if any.
Both components use useActionData
and Form
from react-router-dom
.
import './App.css'; import { EducativeForm, EducativeFormAcion } from './EducativeForm'; import {Route,createBrowserRouter,createRoutesFromElements, RouterProvider} from "react-router-dom"; import Layouts from './layouts/Layouts'; function App() { const educative_router = createBrowserRouter( createRoutesFromElements( <Route path="/" element={<Layouts /> } > <Route path="/educative_forms" element= {<EducativeForm/>} action={EducativeFormAcion}/> </Route> ) ) return ( <> <div className="App"> <RouterProvider router={educative_router} /> </div> </> ); } export default App;
In the EducativeForm.jsx
file:
Lines 2–4: We access the errors generated with useActionData
, if any, after the user enters data. The useActionData
hook saves the errors in the educative_errors
object inside EducativeForm
.
Lines 6–12: We create a form to display to the user. The form has two input tags, one for taking the name as input and the other for age.
Lines 16–17: We verify whether the educative_errors
is not null; if true, we access any error associated with the employee’s name using educative_errors.educative_employee_name
. Similarly, we use educative_errors.educative_employee_age
to display the error generated while inputting age.
Lines 22–26: We create an async function called EducativeFormAction()
that handles form data and input validation. It receives a request object as an argument and retrieves the form data with the request.formData()
method. The stored data, which is saved in educative_data
, is used to save the employee’s name and age in the educative_employee_name
and eduactive_employee_age
objects, respectively. We also initialize an empty educative_errors
object to store all our error messages. These error messages will be displayed to a user when he/she inputs the wrong name or address.
Lines 27–32: We create custom input validation for the form input. In the first if
condition, we check if educative_employee_name
is a number or empty. If true, we assign the error message "Name must be a string, enter your name!"
to educative_errors.educative_employee_name
. Similarly, if age is not a number or not between 18
to 70
, or if the field is empty, we assign "Invalid age, must be a number between 18 and 70"
to educative_errors.educative_employee_age
. These errors will be shown to the user within the form.
Lines 33–36: This condition checks if there are any errors stored in the educative_errors
object. If there are errors, it returns the object containing them. Otherwise, it returns null
.
In App.js
, we have:
Lines 6–13: We create our router object called educative_router
. It contains a path /educative_forms
. Against this, we display the EducativeForm
component and the action function that runs after form submission is EduactiveFormAction
.
useActionData
is a simple and effective way of accessing form data after submission. We can return this data to other components, for example, to display it back to the user or for input validation, as shown above.