Middle
The API response may contain an error that should be displayed to the user next to the corresponding field.
sobes.tech AI
Answer from AI
If the API returns an error related to a specific form field, it is user-friendly to display an error message next to that field.
Typically, the API response includes an error structure where keys correspond to field names, and values are error messages. For example:
{
"errors": {
"email": "Invalid email format",
"password": "Password is too short"
}
}
On the frontend, upon receiving such a response, errors can be linked to form fields and displayed next to the respective input elements.
Example in React:
const [errors, setErrors] = React.useState({});
function handleSubmit() {
api.submitForm(data).catch(response => {
setErrors(response.errors);
});
}
// In JSX
<input name="email" />
{errors.email && <div className="error">{errors.email}</div>}
<input name="password" type="password" />
{errors.password && <div className="error">{errors.password}</div>}
This way, the user immediately sees which fields need correction.