1
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.

1 Answer 1

1

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

hey peter thanks for such fast response. but i want to use the array that i got from fiebase throughout my program outside the value event so how can i do that??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.