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

188
Vistas
function using initial state object instead of using the updated state react

this is my first question, so basically i've a notification object and I've attached a firebase onValue listners which fires the handleNotification function everytime a new value is being added, problem is that the handleNotification fn is not using the updated notification state

const [notification, setNotification] = useState({
  id: '',
  total: '',
  lastTotal: '',
  count: '',
});
 
const handleNotification = (channelId, snap, notification) => {
    console.log('notification before -------', notification);
  if (notification.id === '') {
    let obj = {
      id: channelId,
      total: snap.size,
      lastKnownTotal: snap.size,
      count: 0,
    };
    setNotification({ ...obj });
      return console.log('notification after -------', notification);
  }
  
  // the above if statement runs even when notification.id is already populated, the below code should run instead of that
  
  let obj2 = {
    ...notification,
  };
  if (snap.size - obj2.total > 0) {
    setNotification((prev) => ({ ...prev, count: snap.size - obj2.total }));
  }
};

useEffect(() => {
  const unsubscribe = onValue(
    ref(db, 'messages' + '/' + channel.id),
    (snap) => {
      if (channel) {
        handleNotification(channel.id, snap, notification);
      } else {
        console.log('////');
      } 
    }
  );
  return () => {
    unsubscribe();
  };
}, []);

enter image description here

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

State updates happens in async way, thats why you are still seeing the old state. You can put the console.log outside the function, that will output the updated state.

const handleNotification = (channelId, snap, notification) => {
  console.log('notification before -------', notification);
  if (notification.id === '') {
    let obj = {
      id: channelId,
      total: snap.size,
      lastKnownTotal: snap.size,
      count: 0,
    };
    setNotification({ ...obj });
    return;
  }
  
  // the above if statement runs even when notification.id is already populated, the below code should run instead of that
  
  let obj2 = {
    ...notification,
  };
  if (snap.size - obj2.total > 0) {
    setNotification((prev) => ({ ...prev, count: snap.size - obj2.total }));
  }
};
console.log('notification after -------', notification);

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