I am trying to read data from firebase . But the code works asynchronously and it displays data before fetching it .
I have posted my code
componentDidMount(){
var ref2 = database.ref();
this.getItems(ref2).then((items) => {
this.getResult(items).then((val) => {
// why is this val coming empty
ToastAndroid.show(JSON.stringify(val), ToastAndroid.SHORT);
});
});
}
getItems = async (ref2) => {
var items = [];
await ref2.once('value', snap => {
snap.forEach((child) => {
items.push(child.key);
});
});
// this is working fine . items is correctly returned
return items;
}
getResult = async (items) => {
var response = await this.getFinal(items);
// this response is empty why
return response;
}
getFinal = async (items) => {
var result = [];
await items.forEach((key) => {
ref = database.ref(key);
ref.once('value', snap => {
snap.forEach((child) => {
//val.push(child.val());
var id = child.key;
var data = {
username: child.val().username,
email: child.val().email,
name: child.val().name
};
result.push({[id]:data});
});
});
});
// this result is empty why
return result;
}
I am expecting val to be not empty and also the result to be not empty