I have a React component Forms which includes a form with fields for name, imgUrl, description, and status. Upon submitting the form, the data should be sent to the backend endpoint /api/routes using the fetch API. However, despite no apparent errors in the code, the form data is not being posted to the backend.
Here’s the relevant code snippet:
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
const Forms = () => {
const { register, handleSubmit } = useForm();
const [isLoading, setIsLoading] = useState(false);
const onSubmit = async (data: any) => {
console.log("Form data:", data); // Check form data
try {
setIsLoading(true);
const response = await fetch("/api/routes", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
console.log("Response:", response); // Check response
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage || "Failed to create pet.");
}
console.log("Form data saved successfully!");
} catch (error) {
console.error("Error saving form data:", error);
} finally {
setIsLoading(false);
}
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="space-y-8 px-6">
{/* Form fields */}
<div className="bg-gray-100 px-6 py-4">
<Button variant="ghost" type="submit" disabled={isLoading}>
Upload
</Button>
</div>
</form>
);
};
export default Forms;
i’ve ensured that :
The onSubmit function is correctly triggered upon form submission.
Form data is being logged to the console, and it appears correct.
There are no apparent errors in the fetch request, and the response status seems fine.
Despite this, the form data is not being sent to the backend endpoint. Any insights into what might be causing this issue would be greatly appreciated. Thank you!
Akshat Thapliyal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.