I’m building a blog website using Firebase Firestore and JavaScript. I’m trying to save blog posts to Firestore, but I’m encountering an issue where db is not defined when I attempt to use it in my editor.js file.
Here’s a brief overview of what I’m trying to do:
User Interface: I have an input field for the blog title and a text area for the article content. There’s also an option to upload an image for the banner, which gets displayed at the top of the blog post.
Publishing the Post: When the user clicks the "Publish" button, I want to generate a unique document ID, gather the input data, and store it in Firestore under a new document in the "blogs" collection.
Problem: Despite setting up Firebase and Firestore correctly (or so I think), when I try to use the db variable to interact with Firestore, I get a ReferenceError: db is not defined.
this is my editor.js
const blogTitleField = document.querySelector('.title');
const articleField = document.querySelector('.article');
// banner
const bannerImage = document.querySelector('#banner-upload');
const banner = document.querySelector(".banner");
let bannerPath;
const publishBtn = document.querySelector('.publish-btn');
const uploadInput = document.querySelector('#image-upload');
bannerImage.addEventListener('change', () => {
uploadImage(bannerImage, "banner");
})
uploadInput.addEventListener('change', () => {
uploadImage(uploadInput, "image");
})
const uploadImage = (uploadFile, uploadType) => {
const [file] = uploadFile.files;
if (file && file.type.includes("image")) {
const formdata = new FormData();
formdata.append('image', file);
fetch('/upload', {
method: 'post',
body: formdata
}).then(res => res.json())
.then(data => {
if (uploadType == "image") {
addImage(data, file.name);
} else {
bannerPath = `${location.origin}/${data}`;
banner.style.backgroundImage = `url("${bannerPath}")`;
}
})
} else {
alert("upload Image only");
}
}
const addImage = (imagePath, alt) => {
let curPos = articleField.selectionStart;
let textToInsert = `r![${alt}](${imagePath})r`;
articleField.value = articleField.value.slice(0, curPos) + textToInsert + articleField.value.slice(curPos);
}
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
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(() => {
location.href = `/${docName}`;
})
.catch((err) => {
console.error(err);
})
}
})
this is my firebase installation (firebase.jsm)
Can any one help me plzzz,
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyDQaVM5xjFB-WB4IQXnupSvWOJSQdlrN00",
authDomain: "bloggin-site-c4727.firebaseapp.com",
projectId: "bloggin-site-c4727",
storageBucket: "bloggin-site-c4727.appspot.com",
messagingSenderId: "170432646256",
appId: "1:170432646256:web:f36807db85372e1956f8b5"
};
const app = initializeApp(firebaseConfig);
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export { db };
In my HTML, I’m including the scripts like this:
<script src="https://www.gstatic.com/firebasejs/10.13.0/firebase-app.mjs"></script>
<script src="https://www.gstatic.com/firebasejs/10.13.0/firebase-firestore.mjs"></script>
<script src="js/firebase.js"></script>
<script src="js/home.js"></script>
Here’s a brief overview of what I’m trying to do:
User Interface: I have an input field for the blog title and a text area for the article content. There’s also an option to upload an image for the banner, which gets displayed at the top of the blog post.
Publishing the Post: When the user clicks the "Publish" button, I want to generate a unique document ID, gather the input data, and store it in Firestore under a new document in the "blogs" collection.
Problem: Despite setting up Firebase and Firestore correctly (or so I think), when I try to use the db variable to interact with Firestore, I get a ReferenceError: db is not defined.
However, when I try to publish a blog post,
I get the following error in the console:
Uncaught ReferenceError: db is not defined
at HTMLButtonElement.<anonymous> (editor.js:66:9)
I’m not sure why this is happening, as I’ve correctly exported db from firebase.mjs and imported it in editor.js. I’ve tried including the Firebase SDK via <script> tags as well, but the error persists.
Could anyone point out what might be going wrong here?
Thanks in advance for your help!
2
Answers
Here are some suggestions that might help.
Since it is not clear from your question how is
editor.js
importingdb
and how iseditor.js
included in the project, I am assuming something is not right with those parts.I think you are trying to initialize Firebase using the older
firebase.initializeApp(firebaseConfig);
syntax, which is part of the Firebase namespace approach (used in older versions of Firebase).Secondly, do not forget to import
db
from theeditor.js
fileThirdly, ensure that the
firebase.js
script is loaded BEFOREeditor.js
in your HTML file, especially if you are using<script>
tags directly in the HTML. But I would recommend usingtype="module"
since you are using import/export syntax.Here is more info about modules
Let me know if these tips have helped.
You are mixing "Web modular API" with "Web namespace API".
You can read more at Understand Firebase for Web
Now the issue in you
firebase.jsm
file is that you are importing modular API, but using namespace API properties in the file. Make the following changes(going through with modular API as it is the better choice):Now you can use the
blogsCollection
instance to interact with the collection. You can visit the following link, to learn how to interact with the modular API: Get started with Cloud Firestore.