簡體   English   中英

通過文檔 ID 獲取單個數據 Reactjs Firebase Web ZF20E3C5E54C3AB3D375D66B6

[英]Fetch Single Data by Document Id Reactjs Firebase Web SDK 9

我想通過選定的 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>

以及“查看”頁面中的代碼:

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

非常感謝你的幫助!

您可以使用getDoc() function 獲取單個文檔,如下所示:

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({});
    }
  }
}, [id]);

另請查看: Firestore:在 Web v9 中添加新數據的模式是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM