Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!