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

197
Visualizações
Reactjs doesen't re render after setState to array

when I finish to get data from my database and I useState setValue and pass the array, render function doesen't render again.

Code where I setArray

function getNotifiche(){
     onSnapshot(collection(db, "Users",auth.currentUser.uid, "Notifiche"), async (snapNotifiche) => {
            const notifichee = [];
            snapNotifiche.forEach(async notificaDoc => {

                const docRef = doc(db,"Users",notificaDoc.data().Invitato);
                const userData = await getDoc(docRef);

                
                        notifichee.push({
                            "data":notificaDoc.data(),
                            "invitante":userData.data()
                            })
               });
          
            setListaNotifiche(notifichee);

});

This is in the return function:

 {         
        (listaNotifiche.map((notifica,index)=>{
            return(<div key={index}>
                <label>Invitato da {notifica.invitante.Username} in data{new Date(notifica.data.DataInvito.seconds * 1000).toString()}</label>
                <button>Partecipa</button>
                <button>Elimina</button> 
                </div>);
        }))
    }

So I tried also using setListaNotifiche([...notifichee]) but I get the error: TypeError: Cannot read properties of undefined (reading 'map')

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

0

.forEach doesn't know anything about promises or async functions. By the time the .forEach finishes, notifichee is still an empty array, and then you set state with an empty array. Some time later the array will be mutated to have data, but that comes after the component is rendered.

Instead, you will need to wait for the promises to finish before creating the array and setting state. You can use .map to create an array of promises, then Promise.all to combine them into a single promise, and then await that promise to get the array of data:

onSnapshot(
  collection(db, "Users", auth.currentUser.uid, "Notifiche"),
  async (snapNotifiche) => {
    const promises = snapNotifiche.docs.map(async (notificaDoc) => {
      const docRef = doc(db, "Users", notificaDoc.data().Invitato);
      const userData = await getDoc(docRef);
      return {
        data: notificaDoc.data(),
        invitante: userData.data(),
      }
    })
    const notifichee = await Promise.all(promises);

    setListaNotifiche(notifichee);
  }
);
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