1

I am trying to get data from Firebase realtime database in the loop and set array items, but just the last item can set. it's looking like synchronize problems I tried a lot of things but couldn't solve it.

import FireBaseConnection from '../classes/firebaseconnection.js';

 const  getComments = () => {
    let cardatafetch=[]
     FireBaseConnection.GetData('/PostComments/1234').then((comments) => {
        for (i in comments) {
            cardatafetch.push(comment[i]) 
        }

 for (j in cardatafetch) { 
     var UserId =  cardatafetch[j]["UserID"]   

  FireBaseConnection.GetData('/Users/'+UserId).then((user) => {

     cardatafetch[j].ProfilePicture=user["ProfilePicture"] 
          })
        .catch((error) => {
           console.log(error)
              });
 }
       console.log(cardatafetch)

           }).catch((error) => {
           console.log(error)
              });

 }
    } 

Console Output is

enter image description here

Same problem also during get images from storage

   for (j in cardatafetch) { 
  FireBaseConnection.GetImage().then((obj) => {
     cardatafetch[j].ProfilePicture=obj
          })
             .catch((error) => {
           console.log(error)
              }); 
 }

FireBaseConnection Class

import database from '@react-native-firebase/database';
import storage from '@react-native-firebase/storage';
import { utils } from '@react-native-firebase/app';

 class FireBaseConnection
 {
  static async  GetData(refValue) {
        let data;
 await database()
  .ref(refValue)
  .once('value')
  .then(snapshot => {
    data =  snapshot.val();
  });
  return data;
}

static async  GetImage(imgValue) {
 const reference = storage().ref(imgValue);
 let imagePath= await reference.getDownloadURL().then(result =>result);
return imagePath;
}
}
export default FireBaseConnection;

1 Answer 1

1

Try below code, what I have done is put your code inside last iteration of the loop so it will be implemented only once when all the items are pushed in the array.

import FireBaseConnection from '../classes/firebaseconnection.js';

const getComments = () => {
    return new Promise((resolve, reject) => {
        let commentsArr = [];
        FireBaseConnection.GetData('/PostComments/1234').then((comments) => {
            Object.keys(comments).forEach((key, index) => {
                commentsArr.push(comments[key])

                if(index == Object.keys(comments).length-1) {
                    resolve(commentsArr);
                }
            });
        }).catch((error) => {
            console.log(error)
        });
    });
}

const addImagesToComment = () => {
    this.getComments().then((comments) => {
        var finalArr = [];
        comments.forEach((comment, index) => {
            var tempComment = comment;
            var UserId = comment["UserID"]
            FireBaseConnection.GetData('/Users/' + UserId).then((user) => {
                tempComment.ProfilePicture = user["ProfilePicture"]
                finalArr.push(tempComment);
            }).catch((error) => {
                console.log(error)
            });

            if(index == comments.length-1) {
                console.log(finalArr)
            }
        });
    });
}

Try calling getComments function.

Sign up to request clarification or add additional context in comments.

1 Comment

comments.length not working for json result. i tried const commentLength =Object.keys(comments).length for length it was okey for lenght but still same result. just last item setted

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.