Reputation: 71
I saw that this question was posted 2 days ago. I tried the fixes that solved it for someone else, however I still can't seem to figure out where I'm going wrong. I am trying to get a contact page working using React. Thanks in advance!
import React, { useState } from 'react';
import '../App.css';
import { db } from '../firebase';
const Contact = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
db.collection('contacts')
.add({
name:name,
email:email,
message:message,
})
.then(() => {
alert('Message submitted 👍' );
})
.catch((error) => {
alert(error.message);
});
setName('');
setEmail('');
setMessage('');
};
return (
)
}
export default Contact
firebase.js file:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore'
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
export { db }
Upvotes: 3
Views: 4884
Reputation: 50830
You are not exporting Firestore as db
but the whole Firebase app instance. Try refactoring your code such that it exports Firestore instance as db
:
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
export { db }
Also you are using the new Modular SDK (v9) which has a completely new syntax. I'd recommend following the documentation to understand it. Your query should be:
import { collection, addDoc } from "firebase/firestore";
import {db} from "../firebase"
const handleSubmit = (e) => {
e.preventDefault();
addDoc(collection(db, "contacts"), {
name:name,
email:email,
message:message,
})
.then(() => {
alert('Message submitted 👍' );
})
.catch((error) => {
alert(error.message);
});
setName('');
setEmail('');
setMessage('');
};
Upvotes: 2