justo
justo

Reputation: 3

Cant fetch data from firestore

   const docRef = doc(db, "users", auth.currentUser.uid);
 const docSnap = getDoc(docRef)

 if (docSnap.length) {
  console.log(docSnap.data());
 } else {
// doc.data() will be undefined in this case
console.log("No such document!");
 }

I don't know why docSnap.length is undefined, I tried console logging docsSap.data(), without and if condition and it returns undefined. In firebase, I have the document created. At first, i thought it could be something about firebase permissions but I changed it more than 10 times and still the same

Upvotes: 0

Views: 70

Answers (1)

Zoltán Bata
Zoltán Bata

Reputation: 81

You must use these in asynchronous functions

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-app.js";
import {getFirestore, collection, getDocs, doc, getDoc } from "https://cdnjs.cloudflare.com/ajax/libs/firebase/9.0.1/firebase-firestore-lite.min.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.1/firebase-analytics.js";

const firebaseConfig = {
    apiKey: "Your API_KEY",
    authDomain: "AUTH_DOMAIN",
    databaseURL: "DB_URL",
    projectId: "P_ID",
    storageBucket: "STORAGE BUCKET",
    messagingSenderId: "SENDER_ID",
    appId: "YOUR APP ID",
    measurementId: "M_ID"
};

console.clear() 
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);

const CollectionPath = "MyFirstFirebaseWebsite";
const DocPath = "MyFirstWebsiteDocument";
const WebsiteDoc = await GetWebsitetDoc();
root.innerHTML = TemplateForWebsite(WebsiteDoc);

async function GetDocSnap(){
    const docRef = await doc(db, CollectionPath, DocPath);
    return getDoc(docRef);
}

async function GetWebsitetDoc(){
    const docSnap = await GetDocSnap()
    return docSnap.data();
}

function TemplateForWebsite({firebaselogo, welcome, description, content}){
    return `<div id="logo"><img width="90%" src="${firebaselogo}" /></div>
            <h1>${welcome}</h1>
            <h3>${description}</h3>
            ${content}`
}

Example: https://codepen.io/bzozoo/pen/BarzBRQ?editors=0010

Upvotes: 1

Related Questions