Reputation: 23
REACT NATIVE CODE
constructor(props) {
super(props);
this.state = {
day: '',
month: '',
year: '',
asked_dat: '',
asked_clas: 'CLASS',
asked_su: 'SUBJECT'
};
}
set_date = () => {
this.setState({
asked_dat: this.state.day + '-' + this.state.month + '-' + this.state.year
});
};
retrieve_data = () => {
var asked_date = this.state.asked_dat;
var asked_class = this.state.asked_clas + '/';
var asked_sub = this.state.asked_su;
var date_class = asked_date + '/' + asked_class;
var sub_roll = asked_sub + '/' + 'PRESENT_ROLL_NO';
console.log(date_class + sub_roll);
db.ref(date_class).once('value', function(snapshot) {
console.log(snapshot.child(sub_roll).val());
});
};
when i assign an array variable like temp_arr = snapshot.child(sub_roll).val(); it returns empty array but if console log it i get the array, please help.
Upvotes: 1
Views: 56
Reputation: 80914
If you are assigning an array variable to the result outside the value
event then it will return empty since once()
is asynchronous which means it will not wait until the data is retrieved, therefore if you do this:
db.ref(date_class).once('value', function(snapshot) {
console.log(snapshot.child(sub_roll).val());
});
temp_arr = snapshot.child(sub_roll).val();
};
temp_arr
will return an empty array. You need to do the following:
db.ref(date_class).once('value', function(snapshot) {
temp_arr = snapshot.child(sub_roll).val();
console.log(temp_arr);
});
};
To access it outside the value
event do the following:
retrieve_data = () => {
return new Promise((resolve, reject) => {
var asked_date = this.state.asked_dat;
var asked_class = this.state.asked_clas + '/';
var asked_sub = this.state.asked_su;
var date_class = asked_date + '/' + asked_class;
var sub_roll = asked_sub + '/' + 'PRESENT_ROLL_NO';
console.log(date_class + sub_roll);
db.ref(date_class).once('value', function(snapshot) {
temp_arr = snapshot.child(sub_roll).val();
resolve(temp_arr);
});
});
};
Then when calling the function do the following:
retrieve_data().then((value) => {
console.log(value); //returns array
});
Upvotes: 1