Ravi Shankar
Ravi Shankar

Reputation: 135

How to get single element from firebase

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?

Upvotes: 0

Views: 407

Answers (1)

gil
gil

Reputation: 2552

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");
}

Upvotes: 1

Related Questions