I want to return the snapshot.val()
, of my Realtime Database:
function get_details(){
get(ref(db,"pay/0/0/")).then((snapshot) => {
if (snapshot.exists()) {
var resp = [];
resp.push(snapshot.val());
return resp;
}
}
}
let response = get_details();
console.log(response); //undefined
I keep getting undefined
as the returned value. I have followed the answer from this post.
How do I resolve this issue?
CodePudding user response:
If you are calling get_details
from somewhere else in the code. Try:
async function get_details() {
const snapshot = await get(ref(db, "pay/0/0/"))
return snapshot.val()
}
// get_details() also returns a Promise.
get_details().then((response) => {
// continue
console.log('Value is', response)
})
// Alternatively, if parent function is async
const mainFunc = async () => {
const response = await get_details()
}
Also checkout How do I return the response from an asynchronous call?
CodePudding user response:
As the linked answer states, you have to return the data like this:
function get_details(){
return get(ref(db,"pay/0/0/")).then((snapshot) => {
if (snapshot.exists()) {
return snapshot.val();
}
//Do what you need to if the data doesn't exist.
}
}
Why do you need to do that? Simply, because Firebase API is asynchronous. The solution for this kind of situation is always the same. Any code that needs data from the database, needs to be inside the callback, or be called from there. So the above code will do the trick.