jeudi 23 septembre 2021

How do i use the newest version of firebase with react?

I've searched a lot and can't find a solution... I'm trying to create a PWA using react and firebase with firestore, I have set up the database. When I try to access the content of a collection on the database it returns me a promise which I don't know how to unravel to get the value out. I'll explain with pictures: This is the app.js component I'm trying to fetch an example object from the database

import React, {useState} from "react";
import AppRouter from "./AppRouter";
import { getFirestore, collection, getDocs, doc, getDoc } from 'firebase/firestore/lite';
import { useCollection } from 'react-firebase-hooks/firestore';
import db from "./db";

async function getExamples(){
  const exampleCol = collection(db, 'examples');
  const exampleSnapshot = await getDocs(exampleCol);
  const exampleList = exampleSnapshot.docs.map(doc => doc.data());
  return exampleList;
}

async function getExample(){
  const docRef = doc(db, "examples", "fucPDlEWzuSVN7C4ZaA5");
  const docSnap = await getDoc(docRef);
  const example = docSnap.data();
  return example;
}

const App = () => {
  const example = getExample();
  console.log(example);
  return (
      <div>
          {example.name}
          {/*examples.map(ex1 => <h1>{ex1.name}</h1>)*/}
          <AppRouter />
      </div>
  );
};

export default App;

app.js

database

but when I print the example it is a promise and not an object. console

database connection code:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore/lite";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyBxeF9hwtVsmBVpu4u4EkCcZe1feA3NsjQ",
  authDomain: "g-a-b-5553e.firebaseapp.com",
  projectId: "g-a-b-5553e",
  storageBucket: "g-a-b-5553e.appspot.com",
  messagingSenderId: "696491762097",
  appId: "1:696491762097:web:0d7ef4f1e15ba5165d9d90",
  measurementId: "G-F6TXXQSK5M"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
//const analytics = getAnalytics(app);
const db = getFirestore(app);

export default db;

I just want to be able to access the object and its fields but I can't for the life of me figure it out... any help is appreciated! btw click the links to see prints




Aucun commentaire:

Enregistrer un commentaire