简体   繁体   中英

react-native firebase push snapshots to array

I want to push snapshot i get from firebase to an array so i can map through it, somehow the objects keeps overriding the array instead of appending to the array itself !

here is my function

  _getMessages = async () => {

    await firebase.database().ref('User-Message').child(this.state.fromUser).child(this.state.toUser).on('child_added', async (snapshot) => {

      let message_array = [];

      let message_id = await snapshot.key;

      let message_ref = await firebase.database().ref('Message').child(message_id).once('value', async (payload) => {

        await message_array.push(payload.val())

      })

      console.log(message_array);

    })

  }

it keeps logging like this

[{
    toId : 'id',
    text : 'message',
    fromId : 'id',
    time : timestamp
}]
[{
    toId : 'id',
    text : 'message',
    fromId : 'id',
    time : timestamp
}]
[{
    toId : 'id',
    text : 'message',
    fromId : 'id',
    time : timestamp
}]
[{
    toId : 'id',
    text : 'message',
    fromId : 'id',
    time : timestamp
}]

i want it to be in one array so i can map through it

how may i achieve that ?

只需将您的消息数组放在事件侦听器之外。

_getMessages = () => {
    let message_array = [];
    var isLoaded = false;
    var self = {
        onArrayChanged: () => {
            console.log(message_array);
        },
        currentArray: () => {
            return message_array;
        },
        load: ()=>{
            if(isLoaded)
                return Promise.resolve();
            return new Promise((res,rej)=>{
                firebase.database().ref('User-Message').child(this.state.fromUser).child(this.state.toUser).on('child_added', (snapshot) => {
                    let message_id = snapshot.key;
                    var promiseArray = [];
                    promiseArray.push(new Promise(res1,rej1)=>{
                        firebase.database().ref('Message').child(message_id).once('value', (payload) => {
                            message_array.push(payload.val());
                            if(isLoaded)
                                self.onArrayChanged();
                            else
                                res1();
                        });
                    });
                    Promise.all(promiseArray).then(()=>{
                        isLoaded = true; 
                        res();
                    }).catch(rej);
                });
            });
        }
    };
    return self;
  }

    // Usage

    var messages = _getMessages();
    try{
        await messages.load();
        console.log("loaded");
        console.log(messages.currentArray);
    }catch(e){

    }
firebase.database().ref('Message').once('value') 
  .then((snapshot) => {
    const message_array= [];

     snapshot.forEach((childSnapshot) => {
       message_array.push({
        id: childSnapshot.key,
         ...childSnapshot.val()
       });
     });

I agree with Victor's reply.

_getMessages = async () => {

     await firebase.database().ref('User-Message').child(this.state.fromUser).child(this.state.toUser).on('child_added', async (snapshot) => {

           let message_array = []; // Why is the array initialized everytime on add?

           let message_id = await snapshot.key;    
           let message_ref = await  firebase.database().ref('Message').child(message_id).once('value', async (payload) => {    
              await message_array.push(payload.val())
           }) 

           console.log(message_array);
        })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM