0

I'm using the @react-native-firebase wrapper to interact with Firebase's Firestore. I have a function which performs some querying to one of my collections and the intended response should be an Array object containing each found document.

My function currently looks like:

export const backendCall = async => {
  let response = [] 
  firestore()
  .collection('collection')
  .where('id', '==', 1)
  .onSnapshot(documentSnapshot => {
    documentSnapshot.forEach(x => response.push(x.data())) 
  })
  return response 

On my UI, I use a react-native Button component which calls this function onPress:

<Button 
  title="get" 
  onPress={() => {
    backendCall().then(response => console.log(response)) 
  }}
/> 

Using console.log I am able to observe the expected Array object (but with a "value below was evaluated just now" icon. If however, I change the onPress to console.log(JSON.stringify(response)), the Array object is empty.

I'm assuming this has something to do with the async calls but I can't quite figure out how to fix it. Would appreciate some pointers.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
barte
  • 113
  • 1
  • 4

2 Answers2

1

You're returning the response without waiting for the result from your firebase query. To wait for the response to arrive before returning, you can use Promise.

export const backendCall = () => {
    return new Promise(resolve => {
        firestore()
            .collection('collection')
            .where('id', '==', 1)
            .onSnapshot(documentSnapshot => {
                const response = []
                documentSnapshot.forEach(x => response.push(x.data()))
                resolve(response)
            })
    })
}

You can use Array.map to make the for loop looks nicer.

const response = documentSnapshot.map(x => x.data())
resolve(response)
Duc Nguyen
  • 836
  • 6
  • 12
1

You can also read docs from a QuerySnapshot:

export const backendCall = async () => {
  const qs = firestore().collection('collection').where('id', '==', 1).get()
  return qs.docs.map(x => x.data())
}
Andrew Smith
  • 1,434
  • 13
  • 29