I am trying to send form data to the back end and see it visible in the server console, I am not getting any errors in the front end console when I submit the form but I do not see any sign that the information is being sent, where am I making the mistake?
<Formik
initialValues={{
firstName: "",
lastName: "",
email: "",
Password: "",
ConfirmPassword: "",
}}
validationSchema={SignupSchema}
// on submit handles here
onSubmit={async (values) => {
console.log("logging click");
const {
firstName,
lastName,
email,
Password,
ConfirmPassword,
} = values;
const data = new FormData();
data.append("firstName", firstName);
data.append("lastName", lastName);
data.append("email", email);
data.append("Password", Password);
data.append("ConfirmPassword",ConfirmPassword);
// axios post requst to back end happens here
const form = document.querySelector("form");
if (form) {
form.addEventListener("submit", (e) => {
e.preventDefault();
const FormData = new FormData(form);
axios.post(
"
"http://localhost:8080/api/admin/signup",
FormData,
{
headers: {
"Content-Type":
"multipart/form-data",
},
}
)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
});
}
// same shape as initial values
}}
>
2
Answers
It appears that you have nested event listeners and some unnecessary code in your form submission handling, which might be causing the issue. Here’s a simplified version of how you can send form data to the backend using Axios and Formik:
It seems like the code is attempting to send the form data twice – once using the axios.post method and again using a separate event listener for the form submission. This might be causing confusion and issues with the request.
Try submitting the form directly using axios.post inside the onSubmit and remove the addListener that you are adding. Below is the updated code. Hope it’ll work
For your reference, you can go to your browser developer console and visit the network tab while making a post request. If there is more than one request, it indicates that your code is making redundant requests.