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

149
Views
Filter firebase data in order by timestamp

I am trying to order track ID from firebase by their timestamp (createdAt) but it doesn't seem to order but the function still works. Not sure where I am going wrong on this ?

Any help would be greatly appreciated.

const [trackList, setTrackList] = useState();

//Option 1
    useEffect(() => {
        const userID = localStorage.getItem('id')
        firebase.database().ref(userID)
            .orderByChild('createdAt')
            .once('value', (snapshot) => {
                const firebaseTracks = snapshot.val();
                const trackList = [];
                for (let id in firebaseTracks) {
                    trackList.push({ id, ...firebaseTracks[id] });
                }
                setTrackList(trackList);
            });
    }, []);


//Option 2
useEffect(() => {
        const userID = localStorage.getItem('id')
        const trackRef = firebase.database().ref(userID).orderByChild("createdAt").limitToLast(100);
        trackRef.on('value', (snapshot) => {
            snapshot.forEach(symptomSnapshot => {
                const trackList = [];
                const firebaseTracks = symptomSnapshot.val();
                for (let id in firebaseTracks) {
                    trackList.push({ id, ...firebaseTracks[id] });
                }
                console.log(firebaseTracks)
            });
            setTrackList(trackList);
        });
    }, []);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is when you call snapshot.val() here:

firebase.database().ref(userID)
    .orderByChild('createdAt')
    .once('value', (snapshot) => {
        const firebaseTracks = snapshot.val();

Getting the value of a snapshot returns a JSON object, and the keys in a JSON object are by definition unordered.

To process the results in order, use snapshot.forEach and then call val() on each child:

firebase.database().ref(userID)
    .orderByChild('createdAt')
    .once('value', (snapshot) => {
        const trackList = [];
        snapshot.forEach((child) => {
            trackList.push({ id: child.key, ...child.val() });
        }
        setTrackList(trackList);
    });
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!