I am to make a blog website that can save and publish written articles within the website. I am using firebase firestore to save my data there but only problem is that when i run it, it say db is not defined at HTMLButtonElement
HTML
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js"
></script>
<script
type="module"
src="https://www.gstatic.com/firebasejs/9.1.0/firebase-firestore.js"
></script>
<script type="module" src="js/editor.js">
firebase.initializeApp({
apiKey: "AIzaSyBbHBS9rdHrbP6g7BG4_kPP9XV1vCiVewU",
authDomain: "blog-web-49668.firebaseapp.com",
projectId: "blog-web-49668",
storageBucket: "blog-web-49668.appspot.com",
messagingSenderId: "561111016179",
appId: "1:561111016179:web:eef336738659e3fbfb0d86",
});
var db = firebase.firestore();
db.settings({ timestampsInSnapshots: true });
</script>
Javascprit
publishBtn.addEventListener('click', () => {
if (articleField.value.length && blogTitleField.value.length) {
// generating id
let letters = 'abcdefghijklmnopqrstuvwxyz';
let blogTitle = blogTitleField.value.split("-").join("-");
let id = '';
for (let i = 0; i < 4; i++) {
id += letters[Math.floor(Math.random() * letters.length)];
}
// setting up docName
let docName = `${blogTitle}-${id}`;
let date = new Date(); // for published at info
//access firestore with db variable;
db.collection("blogs").doc(docName).set({
title: blogTitleField.value,
article: articleField.value,
bannerImage: bannerPath,
publishedAt: `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`
})
.then(() => {
console.log('date entered');
})
.catch((err) => {
console.error(err);
});
}
})
You need to remove src="js/editor.js" from the script tag:
<script type="module" src="js/editor.js">
firebase.initializeApp({...
// ...
</script>
should be
<script type="module">
firebase.initializeApp({...
// ...
</script>
i have the same problem, i solve in this way
Hello, try to put this code in the "firebase.js":
let firebaseConfig = {
//your information
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export async function insert(item) {
try {
const response = await db.collection("blogs").add(item);
return response;
} catch (error) {
throw new Error(error);
}
}
export async function getItems(uid) {
try {
let items = [];
const response = await db
.collection("blogs")
.where("userid", "==", uid)
.get();
response.forEach(function (item) {
items.push(item.data());
});
return items;
} catch (error) {
throw new Error(error);
}
}
export async function update(id, completed) {
try {
let docId;
const doc = await db.collection("blogs").where("id", "==", id).get();
doc.forEach((i) => {
docId = i.id;
});
await db.collection("blogs").doc(docId).update({ completed: completed
});
} catch (error) {
throw new Error(error);
}
}
export { db };
and in the js files import:
import { insert, getItems, update, db } from "./firebase.js";