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

178
Visualizações
Passing snapshot to an outer function and receiving data from it

I'm using Firebase here but my question is more general, and not related to Firebase (I think)

Firebase has a snapshot function that serves has a listener for changes:

import { getDatabase, ref, onValue} from "firebase/database";

const db = getDatabase();
const starCountRef = ref(db, 'posts/' + postId + '/starCount');
onValue(starCountRef, (snapshot) => {
  const data = snapshot.val();
  updateStarCount(postElement, data);

});

I'm trying to put that logic in a separate function and receive my changes in my component. The outer function:

export function messagesListener() {
  const db = getDatabase();
  const messagesRef = ref(db, "messages");
  return onValue(messagesRef, (snapshot) => {
    console.log('THERE HAS BEEN A CHANGE');
    const data = snapshot.val();
  });
} 

And in my component:

  useEffect(() => {
    const listener = messagesListener();
  }, []);

But that's incorrect (I don't know how to use that listener to retrieve new data form the snapshot when there is a change). What would be a correct way to do it so that I receive data from the snapshot that resides in that messagesListener function?

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

0

You may try creating a custom hook for that:

function useValueUpdate() {
 const [value, setValue] = useState();
 
 const db = getDatabase();
 const starCountRef = ref(db, 'posts/' + postId + '/starCount');
 onValue(starCountRef, (snapshot) => {
  const data = snapshot.val();
  setValue(data);
 });

 return value;
}

so that it can be used in a component like this:

const dbValue = useValueUpdate();
useEffect(() => {...}, [dbValue]);
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