Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!