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

188
Visualizações
Arrays not getting sorted after async function

On a screen on my app I have a useEffect hook that retrieves some info about a user for a notification, after that I want to get all the notifications array sorted by date, the problem is that the arrays doesn't seem to get sorted:

useEffect(() => {
  const arrayNotifications = [];
  const arrayRequests = [];

  notificationsAndRequests.forEach(async notif => {
    const senderSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
    let senderImage = (senderSnapshot.val() && senderSnapshot.val().userImg);

    if (notif.sender == null) {
      const recieverSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
      senderImage = (recieverSnapshot.val() && recieverSnapshot.val().userImg);
    }

    const element = {
      date: notif.date,
      id: notif.id,
      isInvitation: notif.isInvitation,
      message: notif.message,
      reciever: notif.reciever,
      sender: notif.sender,
      senderimage: senderImage,
      timestamp: notif.timestamp,
      title: notif.title,
      extraid: notif.extraid,
      requestid: notif.requestid,
      viewed: notif.viewed,
      status: notif.status || ''
    };

    if (notif.isInvitation) {
      arrayRequests.push(element);
    } else {
      arrayNotifications.push(element);
    }
  });
  const sortedNotifications = arrayNotifications.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );
  const sortedRequests = arrayRequests.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );

  setNotifications(sortedNotifications);
  setRequestsNotifications(sortedRequests);
}, [notificationsAndRequests]);

Both sortedRequests and sortedNotifications should be ordered by the timestamp property of the notif object (timestamp is just a string formatted as a date). Should I sort both arrayRequests and arrayNotifications instead?

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

0

async on your forEach is not waiting for arrayNotifications and arrayRequests results. You need to wrap your async logic in another function and then update your states there

const sortNotificationsAndRequests = async (notificationsAndRequests) => {
  const arrayNotifications = [];
  const arrayRequests = [];

 for(const notif of notificationsAndRequests) {
   const senderSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
    let senderImage = (senderSnapshot.val() && senderSnapshot.val().userImg);

    if (notif.sender == null) {
      const recieverSnapshot = await database().ref(`/users/${notif.sender}`).once('value');
      senderImage = (recieverSnapshot.val() && recieverSnapshot.val().userImg);
    }

    const element = {
      date: notif.date,
      id: notif.id,
      isInvitation: notif.isInvitation,
      message: notif.message,
      reciever: notif.reciever,
      sender: notif.sender,
      senderimage: senderImage,
      timestamp: notif.timestamp,
      title: notif.title,
      extraid: notif.extraid,
      requestid: notif.requestid,
      viewed: notif.viewed,
      status: notif.status || ''
    };

    if (notif.isInvitation) {
      arrayRequests.push(element);
    } else {
      arrayNotifications.push(element);
    }
 }

  const sortedNotifications = arrayNotifications.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );
  const sortedRequests = arrayRequests.sort(
    (a, b) => Date.parse(mom(b.timestamp, 'YYYY-MM-DD HH:mm').toDate())
    - Date.parse(mom(a.timestamp, 'YYYY-MM-DD HH:mm').toDate())
  );

  setNotifications(sortedNotifications);
  setRequestsNotifications(sortedRequests);
}

useEffect(() => {
  //call the new function to update your states
  sortNotificationsAndRequests(notificationsAndRequests)
}, [notificationsAndRequests]);
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