I am trying to get filtered data from my realtime database. In this example I want to get only these once with a specific uid:
I tried to get the data with the snippet from the firebase docs:
const db = getDatabase();
const auth = getAuth();
const myUserId = auth.currentUser.uid;
const myOffersRef = query(ref(db, 'allOffers/'), orderByChild('uid'), startAt(user.uid));
But how do I get the data from the const myOffersRef
?
Thank you!
CodePudding user response:
As shown in the documentation on reading data, you can use get
to get the data at a path or for a query.
const myOffersRef = query(ref(db, 'allOffers/'), orderByChild('uid'), equalTo(user.uid));
get(myOffersRef).then((snapshot) => {
snapshot.forEach((child) => {
console.log(child.key, child.val().uid);
});
}).catch((error) => {
console.error(error);
});
Note that I also changes startAt
to equalTo
, as you likely only want the nodes that match the UID, not the slide of nodes starting from the first match (which is what startAt
does).
The forEach
is needed since a query can potentially have multiple results, so the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.