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

187
Visualizações
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 Respostas
Responde à pergunta

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 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