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!
CodePudding user response:
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?