Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

196
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda