Home > Software design >  How to get single element from firebase
How to get single element from firebase

Time:04-04

I fetch all the data from the firebase database, showing it in the list. Now what I want do when I click on a particular element, all the data of that particular element only fetch. I am using Next.js/react.js a basic file that manages firebase connection

`// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app"

import { getFirestore } from "@firebase/firestore"
// 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: "A#########################I",
  authDomain: "clion-project.firebaseapp.com",
  projectId: "clion-project",
  storageBucket: "clion-project.appspot.com",
  messagingSenderId: "8#########",
  appId: "1:86735948933:web:46352###############",
  measurementId: "G-KZG7P8MRW2",
}

// Initialize Firebase
const app = initializeApp(firebaseConfig)
export const db = getFirestore(app)

` How I am getting the list of elements:

  const usersCollectionRef = collection(db, "Patients") 
  const [user, setUsers] = useState([])
  const q = query(usersCollectionRef)
    onSnapshot(q, (QuerySnapshot) => {
      setUsers(
        QuerySnapshot.docs.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }))
      )
    })

Now How I query a particular element from the list using its ID?

CodePudding user response:

assuming you have your particular element document id you can do it this way:

const docRef = doc(db, "Patients", "<your element doc id>");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Doc data:", docSnap.data());
} else {
  console.log("doc doesn't exists");
}
  • Related