Firebase .data() function is not found - javascript

I did manually set up the entire data into Firebase Firestore have been trying to retrieve the data as followed
import app, { db } from "./app";
import {
addDoc,
collection,
doc,
getDocs,
getFirestore,
limit,
orderBy,
query,
setDoc,
Timestamp,
} from "firebase/firestore";
export default async function getEvents() {
const db = getFirestore(app);
const first = collection(db, "Events");
const docSnap = await getDocs(first);
console.log(docSnap.data());
}
The thing over here is that the console throws an error saying that docSnap.data() is not a function
TypeError: docSnap.data is not a function

Yes apparently the mistake I did was that I need to specify the document before I get it's data, So the correct thing to do would be
console.log(docSnap.docs[0].data());
If you want all the data from all the elements maybe you can loop over them or just map them depending over your preference.

Related

Firebase JS Uncaught (in promise) TypeError: doc is not a function

I'm working on a web app using firebase and encountered this error. After a few hours of debugging, I still haven't been able to understand what's wrong, I'll leave the code here for anyone who can help me figure out what its is that I'm doing wrong. Any suggestion will be really helpful, thanks!
Code:
import {
getFirestore,
addDoc,
doc,
updateDoc,
collection,
query,
where,
getDocs,
setDoc,
} from "firebase/firestore";
const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);
var files = [....]
getDocs(collection(firestore, "property")).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (files.includes(decrypt(doc.data().fileno))) {
if (files.includes(decrypt(doc.data().fileno), 6)) {
let owner = "ABC";
const bref = doc(collection(firestore, "property"), doc.id);
updateDoc(bref,{owner:encrypt(owner)}).then(()=>{
console.log("updated")
})
} else {
let owner = "XYZ";
const bref = doc(collection(firestore, "property"), doc.id);
updateDoc(bref,{owner:encrypt(owner)}).then(()=>{
console.log("updated")
})
}
}
});
});
You have two definitions of doc in your code:
The doc function that you import from the Firestore SDK
The doc parameter that you declare in querySnapshot.forEach((doc) => {.
The second doc hides the first one, which is why you can't call the doc function anymore inside that callback.
The solution is to give the variable a different name, like docSnapshot.

"query is not a function" Next Js getServerSideprops and firebase error

I'm using NextJS and firebase as my primary database for the app that I'm currently building for an NGO. and I ran into an issue.
import {
collection,
where,
query,
getDocs
} from '#firebase/firestore';
import { db } from '../../../services/firebase';
export async function getServerSideProps({query}) {
const user = await getDocs(query(collection(db, 'members'), where('id', '==', query)))
return {
props: {
// VisionInfo: JSON.stringify(user.docs.map(item => item.data()))
json: JSON.stringify('Hello')
}
};
}
The only way to get Query from the URL in NextJS in serverSideProps is to use the keyword "query" but the same keyword is used to fetch firebase document.
The error shows "query is not a function"
Is there anyway I could get Query into serversideprops ?
The issue arises because you also have "query" in getServerSideProps parameters. Try naming the import from Firestore SDK (or the query param) as shown below:
import { query as fireQuery } from '#firebase/firestore';
export async function getServerSideProps({query}) {
const user = await getDocs(fireQuery(collection(db, 'members'), where('id', '==', query)))
// use fireQuery here ^^^
})

Objects taken from Firebase are inaccessible after being pushed into an array through a forEach loop

I've been trying to create a chat app using react and firebase just for practice since I wanted to try out Firebase, and although I'm able to print out the array of objects that I retrieved into the console, I can't seem to access those objects directly... For example:
if I code "console.log(testArray);" this is what displays in the console, which is all good
0: {name: 'JohnDoe', profile_image: 'imaginary image URL', date: it, message: 'This is my first message to Firebase!'}
but if I try console.log(testArray[0]); it displays undefined in the console
Here's my code
import Config from './config';
import { initializeApp } from "firebase/app";
import {
getFirestore,
addDoc,
getDocs,
collection,
query,
orderBy
} from "firebase/firestore";
function App() {
const firebaseApp = initializeApp(Config);
const firestore = getFirestore();
const chat_collection = collection(firestore, "chat");
const addData = () => {
addDoc(chat_collection, {
date: new Date(),
message: document.getElementById("message").value,
name: "JohnDoe",
profile_image: "imaginary image URL"
});
}
let testArray = [];
const readData = async () => {
const chatAppQuery = query(
collection(firestore, 'chat'),
orderBy('date')
);
const chatSnapshot = await getDocs(chatAppQuery);
chatSnapshot.forEach((message) => {
testArray.push({
name: message.data().name,
profile_image: message.data().profile_image,
date: message.data().date,
message: message.data().message
});
});
}
readData();
console.log(testArray);
console.log(testArray[0]);
My first time asking for help on here, I'd deeply appreciate it!
Since readData is an async function, you need to use await (or then() to wait for it results.
So:
await readData();
// 👆
console.log(testArray);
console.log(testArray[0]);
If you're in a context where you can't use async/await, you can also use then:
readData().then(() => {
// 👆
console.log(testArray);
console.log(testArray[0]);
})

How to get server Timestamp from firebase v9?

Please, I need your help to get the server timestamp from Firebase version 9.
I've tried to follow the same approach as for Firebase v8 : firebase.firestore.FieldValue.serverTimeStamp() but didn't work for version 9.
Is there any way to do the same thing in Firebase version 9 ?
It's discussed in the documentation. Just import serverTimestamp.
import { updateDoc, serverTimestamp } from "firebase/firestore";
const docRef = doc(db, 'objects', 'some-id');
// Update the timestamp field with the value from the server
const updateTimestamp = await updateDoc(docRef, {
timestamp: serverTimestamp()
});
If you get type error with other answers you can try this:
import { Timestamp} from '#firebase/firestore';
createdAt: Timestamp.fromDate(new Date())
import {serverTimestamp} from 'firebase/firestore';
Then simply change timestamp: firebase.firestore.FieldValue.serverTimestamp() to timestamp: serverTimestamp()
Firestore Database V9:
import { doc, updateDoc, serverTimestamp, getFirestore } from "firebase/firestore";
const db = getFirestore(app);
const docRef = doc(db, 'yourCollection', 'yourDocId');
await updateDoc(docRef, {
timestamp: serverTimestamp()
});
Firebase Realtime Database V9:
import { serverTimestamp, ref as fbRef, getDatabase, update } from 'firebase/database';
const db = getDatabase(app);
const yourUpdatedDoc = {
lastUpdated: serverTimestamp()
}
await update(
fbRef(db, `/yourDocLocation`), yourUpdatedDoc
);
If anyone is looking for an answer of this question
import { serverTimestamp } from 'firebase/firestore/lite';
lastSeen: serverTimestamp()

weird behavior await running without async

I was running firebase when I saw a strange behavior which I am unable to understand. My html looks like this:
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-firestore.js"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp, } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getFirestore, collection, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
const firebaseConfig = { ... } //firebase config
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const querySnapshot = await getDocs(collection(db, "location")); *** //await is running without async! ***
console.log(querySnapshot)
querySnapshot.forEach((doc, index) => {
// do something with doc
*** // index always returns undefined! ***
}
Problem 1: Async running without await.
Problem 2: Index is undefined after reading and iterating data from firebase.
Please help as I studied js for more than a year and I feel like a complete newbie now.
Thank You Bergi (Profile):
It is indeed a top level await (a feature in moduleJS).
Read more about it here: https://v8.dev/features/top-level-await
Thanks! Dharamraj (Profile) => querySnapshot.docs.forEach() index works perfectly fine now.

Categories

Resources