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

108
Visualizações
My flatList is rendering before my api query finishes

I have this async function called getRecados() that reaches out to firebase and grab all the data I will need my flatlist to render:

const getRecados = () => {
    setRefreshing(true)
    try {
      const recadosRef = firebase.firestore().collection('recados');
      recadosRef.orderBy('timestamp', 'desc').get().then(snapshot => {
        const recadosList = new Array()
        // Does some filtering on the data it just grabbed from firebase
        if (user_setor.length == 0) {
          snapshot.forEach(doc => {
            if ((doc.data().curso_dest == user_curso
              || doc.data().curso_dest == '')
              && (doc.data().ano_dest == user_ano
                || doc.data().ano_dest == '')
              && (doc.data().turno_dest == user_turno
                || doc.data().turno_dest == ''))
              recadosList.push(doc)
          })
        } else {
          snapshot.forEach(doc => {
            if (user_setor.includes(doc.data().remetente)) {
              recadosList.push(doc)
            }
          })
        }
        // fullData is an useState
        setFullData(recadosList.map((doc) => ({
          id: doc.id,
          titulo: doc.data().titulo,
          timestamp: doc.data().timestamp,
          remetente: doc.data().remetente,
          curso_dest: doc.data().curso_dest,
          ano_dest: doc.data().ano_dest,
          turno_dest: doc.data().turno_dest,
          texto: doc.data().texto
        })))
        setLoading(false)
        setRecados(fullData)
      })

    } catch (err) {
      Alert.alert("Erro ao consultar os recados!!!", err.message);
    }
    setRefreshing(false)
  };

And I call it as soon as the homeScreen renders with:

useEffect(() => {
    getRecados()
  }, []);

But when I open the homeScreen for the first time the flatList is empty, but when I execute getRecados() again with a button the flatList works fine and displays the data from firebase, so that made me conclude that the flatList is rendering before getRecados() can set fullData's value for the first time, so how do I make it wait for getRecados to finish whatever its doing?

Here's the flatlist code:

<FlatList 
  data={recados}
  onRefresh={getRecados}
  refreshing={refreshing}
  showsVerticalScrollIndicator={false}
  renderItem={({ item }) => (
    <Card
      texto={item.texto}
      titulo={item.titulo}
      timestamp={item.timestamp}
      info1={item.remetente}
      info2={
        "ao " + item.ano_dest + "º " + item.curso_dest + " " + item.turno_dest
      }
    />
  )}
/>;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I tried Ashish's suggestion of using Promise/Then instead of Async/Await and it kind of worked, using .get().then() did solve the problem of the data not loading on useEffect but it just loaded 4 of the 15 documents I had on firebase for some reason, so what worked for me was to use firebase's .onSnapshot() function insted of .get(), here's the resulting code:

const getRecados = async () => {
    setRefreshing(true);
    try {
      const recadosRecebidos = firebase
        .firestore()
        .collection("recados")
        .orderBy("timestamp", "desc")
        .onSnapshot(
          snapshot => {
               /*
                * Just filtering the data, has nothing to do with the problem;
                */
            }
              return result
            }, []);
            setFullData(recadosList);
            setRecados(recadosList);
          },
          () => {
            setError(true);
          }
        );
      setLoading(false);
    } catch (err) {
      Alert.alert("Erro ao consultar os recados!!!", err.message);
    }
    setRefreshing(false);
  };
about 4 years ago · Juan Pablo Isaza Relatório

0

Simply have a condition for not to show FlatList until your api call is done. You are already managing loading variable so utilise that only like

if(loading){
    // Show loader or actvityIndicator
}
else{
    // Your flat list code.
}
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