Search code examples
arraysreactjsreact-nativeuse-statearray-push

push object to array react native


I need to get specific users who have the serviceClientID field in the firestore.

those that do, I insert it into the array and put it in my state chats (setChat).

but the problem is that only one user is entering my state and I have two users with this field.

why is only 1 entering and not 2?

code below:

firebase.auth().onAuthStateChanged(async ({ uid }) => {
          const servicesCollection = await firestore()
            .collection('Providers')
            .doc(uid)
            .collection('ServiceHistory')
            .get();
          servicesCollection.docs.forEach(async item => {
            if (item.exists && item.data().serviceClientID) {
              const clientsCollection = await firestore()
                .collection('Clients')
                .doc(item.data().serviceClientID)
                .get();

              // if (item.data().serviceClientID === clientsCollection.id) {
              const values = {
                id: clientsCollection.id,
                name: clientsCollection.data().name.last,
                uid,
              };
              const arr = [];

              arr.push(values);
              // }
              console.log('arrayay', arr);

              setChats(arr);
            }
          });
        });

Solution

  • Cause every loop you empty an array. You have to get the {arr} out of the function. then you need to push the data inside.

    const firebaseFunc =  () => {
          let arr = [];
    
          firebase.auth().onAuthStateChanged(async ({ uid }) => {
            const servicesCollection = await firestore()
                .collection('Providers')
                .doc(uid)
                .collection('ServiceHistory')
                .get();
            servicesCollection.docs.forEach(async item => {
              if (item.exists && item.data().serviceClientID) {
                const clientsCollection = await firestore()
                    .collection('Clients')
                    .doc(item.data().serviceClientID)
                    .get();
                arr.push({
                  id: clientsCollection.id,
                  name: clientsCollection.data().name.last,
                  uid,
                });
              });
          });
    
          setChats(arr);
          console.log('arrayay', arr);
        }