Introduction
Do you want to know how to display your validation errors on the frontend of your application? Then, follow along! If you have your backend set up properly, you should have a private method in your application controller that displays an object with the key, errors. It should look something like this:
class ApplicationController < ActionController::API
rescue_from ActiveRecord::RecordInvalid, with: :invalid
...
private
def invalid(e)
render json: { errors: e.record.errors.full_messages },
status: :unprocessable_entity
end
Displaying Errors on Frontend
Now that you have your backend set up, we can move to the frontend to display these errors for the user. In the component where we would like our errors to be shown, we will need set a state for these errors with an initial value as an empty array ([]).
import React, {useState, useEffect} from 'react';
export default function OurComponentFunction() {
const [errors, setErrors] = useState([])
...
}
Then, wherever you are fetching the data for which you want the errors to be displayed, you will need to create an if statement. The if statement will state that if there are errors associated with the data, then you will set the errors state with those specific errors. If there are no errors, then the frontend will carry on as expected and display the data needing to be displayed. In the example below, we fetching from "food" and trying to create a new food post.
function handle Submit(e) {
e.preventDefault();
fetch("/food", {
method: "POST",
headers: {
"Content-Type": "application/json",
accepts: "application/json",
},
body: JSON.stringify({
name: name,
category: category
}),
})
.then((r) => r.json())
.then((data) => {
if(data.errors) {
setErrors(data.errors)
} else {
addNewFoodToArray(data)
}
})
}
Now, that we have our errors being set in the errors state, we need to render it so that it can be shown on the application browser for the user. We will need to map through all the errors in the errors state so that we can return each error individually in an element tag of your choice. In the example below, we are using the 'p' tag.
return (
...
{errors.map((error) => {
return <p>{error}</p>
}
)
Conclusion
Finally, you have the tools and knowledge to try displaying your own errors on your application browser for the user to see! Go ahead and give it a try!
Top comments (0)