Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
Get Firebase Collection into simple array

I am trying to react all items from a collection in Firebase into an array so I can use later in React.

I have this currently:

  const retrievegear = firebase.firestore().collection('gear').get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      const check = doc.data().Name;
        console.log(check);
    });
  });

Which is fine - it shows me all the Names of the items in the gear collection. But I want it within an array and only want some of the fields in the collection.

I am then using this array to populate checkboxes - so I need const declared somewhere so that my return can access it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The Firestore get() method is asynchronous and returns a Promise, so it’s only in the callback function passed to then() that you get its result.

Consequently you need to do as follows:

const myArray = [];
firebase.firestore().collection('gear').get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      const check = doc.data().Name;
        console.log(check);
        myArray.push(check);
    });
    // Here do whatever you want with the myArray array which contains the data from the collection

  });

If you want to transform this code in a function that you can call from other places in your code, do as follows (we use async/await for readability):

async function getGearData() {
    const myArray = [];
    const querySnapshot = await firebase.firestore().collection('gear').get();
    querySnapshot.forEach(doc => {
        const check = doc.data().Name;
        console.log(check);
        myArray.push(check);
    });
    return myArray;
}

Note that this function is asynchronous, so you need to call it as follows:

getGearData()
.then(gearData => {
  // Here and only here you get the value 
  console.log(gearData);
  // ....
})

Note that you can also use the map() method on the array returned by querySnapshot.docs.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda