Please help. I've been trying for days, watched countless tutorials, and tried different combination of methods on Firebase documentations, but nothing seemed to work.
I'm building a Vue chat project and trying to write data into firebase databases. The code in my firebase/init.js is as follows:
import { initializeApp } from "firebase/app";
import { getFirestore} from 'firebase/firestore';
const firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXX"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export default db;
The code in my CreateMessage.vue file is as follows:
<script>
import {collection, addDoc} from "firebase/firestore";
export default {
name: 'CreateMessage',
props: ['name'],
data() {
return {
newMessage: null,
errorText: null
}
},
methods: {
createMessage () {
if (this.newMessage != "") {
addDoc(collection(firestore, "messages"),{
message: this.newMessage,
name: this.name,
timestamp: Date.now()
});
this.newMessage = null;
this.errorText = null;
} else {
this.errorText = "A message must be entered first!";
}
}
}
}
</script>
Any help would be greatly appreciated. Thank you all very much in advance.
The only thing you are exporting from your init.js file is db. And you never import db into your component. Should import like this
import { db } from 'firebase/init.js
and then add the doc...
addDoc(collection(db, 'messages'), ...
Alternatively, you don't have to import db. You could just also import getFirestore from firebase/firestore and just do...
addDoc(collection(getFirestore(), 'messages'), ...