0

I want to fetch the data from single document by selected ID. I have try with function "child" and "orderByChild" but it seems did not work with web SDK 9. Could you please to help with the new format query of web version 9. Below is my code at table database:

<Link to={`/view/${id}`}>
    {id.data.dateCreate}
</Link>

And the code in "View" page:

const [user, setUser] = useState({});
const { id } = useParams();
useEffect(() => {
    db
      .orderByChild(`reports/${id}`)
      .get()
      .then((snapshot) => {
        if (snapshot.exists()) {
          setUser({ ...snapshot.val() });
        } else {
          setUser({});
        }
      });
  }, [id]);

Thank you so much for your help!

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Chris Ho
  • 7
  • 4
  • 1
    Where is `db` coming from? It should be Firestore instance (`const db = getFirestore()`) when using my answer below. – Dharmaraj Aug 21 '22 at 19:07

1 Answers1

1

You can use getDoc() function to fetch a single document as shown below:

import { doc, getDoc } from "firebase/firestore";

useEffect(() => {
  const fetchDocById = async () => {
    // Create DocumentReference
    const docRef = doc(db, "reports", id) // db = getFirestore()
    
    // Fetch document
    const docSnap = await getDoc(docRef)
    
    if (snapshot.exists()) {
      setUser({
        ...snapshot.val()
      });
    } else {
      setUser({});
    }
  }

  fetchDocById()
}, [id]);

Also checkout: Firestore: What's the pattern for adding new data in Web v9?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Thank you for your response but it still not works, it might come from the line of code since the array of user has returned empty – Chris Ho Aug 22 '22 at 18:20
  • I have fixed it. Thank you for your help. Btw, I need to change snapshot to docSnap to make it work. Anyway, thank you so much bro! – Chris Ho Aug 22 '22 at 18:55