Home > front end >  How to print out data keys from firebase with JavaScript?
How to print out data keys from firebase with JavaScript?

Time:08-24

I've been reading the FB docs and watching some youtube videos/tuts and I'm trying to print out the keys/data I have from my FB database. (I'm learning firebase). My end goal is to display the data on React Native app.

But all I get is

{"_query": {"C": null, "D": null, "collectionGroup": null, "endAt": null, "explicitOrderBy": [[Ne]], "filters": [], "limit": null, "limitType": "F", "path": {"len": 1, "offset": 0, "segments": [Array]}, "startAt": null}, "converter": null, "firestore": {"app": [FirebaseAppImpl], "databaseId": [Dt], "settings": [wc]}, "type": "query"}

and

{"_path": {"len": 1, "offset": 0, "segments": ["users"]}, "_query": {"C": null, "D": null, "collectionGroup": null, "endAt": null, "explicitOrderBy": [], "filters": [], "limit": null, "limitType": "F", "path": {"len": 1, "offset": 0, "segments": [Array]}, "startAt": null}, "converter": null, "firestore": {"app": [FirebaseAppImpl], "databaseId": [Dt], "settings": [wc]}, "type": "collection"}

Here's my code, any advice or help will be much appreciated.

const [users, setUsers] = useState([]);

useEffect(() => {
  const collectionRef = collection(db,'users');
  const q = query(collectionRef, orderBy('nombre', 'desc'))

  console.log(collectionRef)
  console.log(q)


CodePudding user response:

With query(collectionRef, orderBy('nombre', 'desc')) you actually define a Query.

To get the document(s) corresponding to this query you need to use the asynchronous getDocs() method, as follows:

import { collection, query, orderBy, getDocs } from "firebase/firestore";

const q = query(collectionRef, orderBy('nombre', 'desc'));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

Same code with then():

const q = query(collectionRef, orderBy('nombre', 'desc'));

getDocs(q).
then(querySnapshot => {
    querySnapshot.forEach((doc) => {
      console.log(doc.id, " => ", doc.data());
    });
});
  • Related