I’m facing an issue with the getDoc function in Firebase Firestore. When I try to use getDoc to retrieve a document from the Firestore database in my web application, it neither resolves nor throws any errors.
Here’s my code snippet in js:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js';
import { getFirestore, collection, addDoc, doc, setDoc, getDoc, query, getDocs, onSnapshot, updateDoc, where } from 'https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js';
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
const app = initializeApp(config);
const db = getFirestore(app);
[... other functions]
async function cropImage() {
if (!selectedUser) {
return;
}
try {
const imageDataURL = croppedCanvas.toDataURL();
const cleanedURL = cleanAndValidateUrl(imageDataURL);
if (!cleanedURL) {
console.error('Invalid image URL');
return;
}
const userDocRef = doc(db, 'character_sheet', selectedUser);
const imagesCollectionRef = collection(userDocRef, 'images');
try {
const imagesCollectionSnapshot = await getDocs(imagesCollectionRef); //HERE THE CODE STOPS, RETURNING NOTHING
if (!imagesCollectionSnapshot.empty) {
// If the collection doesn't exist, create it
await addDoc(imagesCollectionRef, {});
}
} catch (error) {
console.error("Error retrieving images collection:", error);
}
// Get a reference to a new document in the images collection
var newImageRef = doc(imagesCollectionRef);
// Clean and validate the image URL
const cleanedImageUrl = cleanAndValidateUrl($('#previewImage').attr('src'));
if (typeof cleanedImageUrl !== 'string') {
console.error('Cleaned image URL is not a string:', cleanedImageUrl);
return;
}
// Set the document data (image)
await setDoc(newImageRef, {
imageUrl: cleanedImageUrl,
cropData: {
x: croppedData.x,
y: croppedData.y,
width: croppedData.width,
height: croppedData.height,
rotate: croppedData.rotate,
scaleX: croppedData.scaleX,
scaleY: croppedData.scaleY
}
});
// Display success message
alert("Image uploaded successfully.");
// Clear the preview
$('#previewImage').attr('src', '');
cropper.destroy();
console.log('Image uploaded successfully');
} catch (error) {
console.error('Error uploading image:', error);
}
}
When I run this code, the error block inside the catch statement is not executed. However, I can confirm that the document exists in the Firestore database, and the Firebase configuration is correct.
Interestingly, when I try to access the same collection and document from another page using getDoc, it works perfectly fine.
Could anyone provide insights into why getDoc might not be resolving or throwing errors in this scenario? Any help would be greatly appreciated. Thank you!