Hi,
I am using useForm to validate my form, as shown in the examples on @Shopify_77 /react-form. Everything works fine on the frontend, but I want to validate the data on the backend as well. However, since I am new to frontend solutions, I am having trouble understanding how to handle the onSubmit function.
According to the documentation, onSubmit should be async and return either a success or fail status, along with any error messages. However, I am having trouble getting the error messages to show up.
After doing some research, I found a solution that works for me:
- If the server responds with a status code of 200, show a Toast with a success message.
- If the server responds with a status code of 400, show a Toast with an error message and save the errors for specific fields using the setErrors method.
- If the server responds with any other error code, show a Toast with the message “Please try again.”
I would like to explore other solutions to learn more about how this should work.
const onSubmit = useCallback(async (formData) => {
const endpoint = "/api/item";
try {
const response = await fetch(endpoint, {
method: 'POST',
body: JSON.stringify(formData),
headers: {
'Content-Type': 'application/json'
}
});
if (!response.ok) {
if (response.status === 400) {
const data = await response.json();
console.log(data);
title.setError('error');
throw new Error('400 error')
}
throw new Error('some error')
}
return {status: 'success'};
} catch (error) {
return {status: 'fail', error: [error]};
}
}, [item, setItem]);