![](/img/trans.png)
[英]How to fetch a single data value out of firebase database with reactjs
[英]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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.