'Issue: React contact form increments every API call n +1 times after every submission and doesn't submit after first click
I'm building out a contact form for my portfolio web app using Firebase Firestore as the database for the form input data.
1st issue: When I click the submit button it doesn't execute the API call to write the input data to the database on the first try, but it works every time after that in the first try.
2nd issue: Every form submission after the first initial submit keeps incrementing the API call by n + 1.
(e.g. the second time I try to submit the form the input data records twice in the data base. The third time I try to submit the form, the data records three times in the data base for the same input... and so on.)
I am fairly new to React and JS so thanks in advance!
import React from "react";
import './contact.css';
import { initializeApp } from "firebase/app";
import {
getFirestore, collection, getDocs, addDoc
} from 'firebase/firestore';
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx",
projectId: "xxxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxxx",
appId: "xxxxxx"
};
// Initializing the Firebase Firestore database
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const colRef = collection(db, 'contacts')
// Read the existing documents from the database and console.log them
const findDocs = () => {
getDocs(colRef)
.then((snapshot) => {
let contacts = []
snapshot.docs.forEach((doc) => {
contacts.push({ ...doc.data(), id: doc.id })
})
console.log(contacts)
})
.catch(err => {
console.log(err.message)
})
}
// Handling the contact form submission
const handleSubmit = (e) => {
findDocs();
e.preventDefault();
const addContactForm = document.querySelector('.add');
addContactForm.addEventListener('submit', async (e) => {
e.preventDefault();
await addDoc(colRef, {
name: addContactForm.name.value,
email: addContactForm.email.value,
message: addContactForm.message.value,
})
.then( () => {
addContactForm.reset();
console.log('Form submitted');
})
})
}
function Contact() {
return (
<form onSubmit={handleSubmit} className="add" >
<h1 className="contact-form-h1" >Contact Me</h1>
<h5 className="replying-shortly">I will be replying shortly!</h5>
<label className="form-headings" htmlFor="name">Name</label>
<input type="text" name='name' placeholder="Name" required />
<label className="form-headings" >Email</label>
<input placeholder="Email" type="text" name='email' required />
<label className="form-headings" >Message</label>
<textarea placeholder="Message" type="text"
name='message' required>
</textarea>
<button type="submit">Submit</button>
</form>
);
};
export default Contact;
Solution 1:[1]
With the help of @CarlosSpohr I was able to solve my problem by realizing that I was adding a submit event twice.
One was from the 'onSubmit' form attribute and the second one was from the '.addEventListener' method. After deleting it, my form now submits on the first try and doesn't write the same data multiple times to the database.
// Handling the contact post submission
const handleSubmit = (e) => {
e.preventDefault();
findDocs();
// Writing input data to database
const addContactForm = document.querySelector('.add');
e.preventDefault();
addDoc(colRef, {
name: addContactForm.name.value,
email: addContactForm.email.value,
message: addContactForm.message.value,
})
.then( () => {
addContactForm.reset();
console.log('Form submitted');
})
alert("Message submitted! Someone will be contacting you back shortly.")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
