0

I'm working with react in combination with firebase. I'm trying to export all firebase stuff to separate files but strugeling with the return of an array. Which is kind of .. well.

I have App.js which looks similar to this:

import { getDataFromFirebase } from './somewhere'

export default function App() {
  useEffect(() => {
    setA(getDataFromFirebase())
  }, [])

  const [a, setA] = useState([])

Then I have the firebase file with one get function which looks like this:

export function getDataFromFirebase() {
  let aArr = []
  db
    .collection('user')
    .get()
    .then(function(querySnapshot) {
      querySnapshot.forEach(function(doc) {
        let aObj = doc.data()
        aObj._id = doc.id
        aArr = [...aArr, aObj]
      })
    })
}

This way I'm ending up with aArr which includes all users + their id. Now I've tried to pass the array to app so I can use it there but it won't work. All I get is undefined when I try to return aArr in line 10. I'm clearly missing something. Can anyone help?

kdc
  • 77
  • 1
  • 11
  • 1
    Return the promise from the function (`return db...`). Return the array from the `.then` callback. Wait for the promise to resolve: `getDataFromFirebase().then(setA)`. FWIW, `getDataFromFirebase` is not a React component. – Felix Kling Jan 17 '20 at 23:34
  • Thank you for your answer but even after I read half of the other thread it's still not working. I wrote it as you suggested. return db .collection('dogs') .get() .then(function(querySnapshot) { querySnapshot.forEach(function(animal) { let animalObj = animal.data() animalObj._id = animal.id animalArr = [...animalArr || [], animalObj] return animalArr }) }) In the other file is: getAnimals().then(setAnimalList) But I don't get no array but another promise which I don't know how to handle. – kdc Jan 18 '20 at 11:15
  • 1
    `getAnimals().then(setA)` returns a promise, yes, but that shouldn't matter because you are passing `setA` to `.then` which will receive the result array. Don't do `setA(getAnimals()...)`, that would be wrong. Also you have to return the array from the `.then` callback not the `.forEach` callback. – Felix Kling Jan 19 '20 at 09:14

0 Answers0