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.

0

2 Answers 2

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

1 Comment

That's very helpful. Thank you.
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())
}

Comments

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.