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);
});
}, []);
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);
});