I have this construction for reading data from Firebase (it's for 8 version Firebase).
const info = (await firebase.database().ref(`/users/${uid}/info`).once('value')).val
But I use version 9 Firebase. I saw example in Firebase manual, but can't adapt for my example.
These examples from manual: (version 9)
import { getDatabase, ref, onValue } from "firebase/database";
import { getAuth } from "firebase/auth";
const db = getDatabase();
const auth = getAuth();
const userId = auth.currentUser.uid;
return onValue(ref(db, '/users/' userId), (snapshot) => {
const username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
// ...
}, {
onlyOnce: true
});
(Version 8):
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/users/' userId).once('value').then((snapshot) => {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
// ...
});
CodePudding user response:
onValue()
sets a listener for data changes at a particular location.
In your case, you want to read the data once since you use the once()
method in V8.
So the corresponding V9 syntax is:
import { getDatabase, ref, child, get } from "firebase/database";
const dbRef = ref(getDatabase());
get(child(dbRef, `/users/${uid}/info`)).then((snapshot) => {
if (snapshot.exists()) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous';
// ...
} else {
console.log("No data available");
}
}).catch((error) => {
console.error(error);
});
More details in the doc.