I've the following dataset on a real-time Firebase database:
{
"posts": {
"key1": {
message: "message",
title: "title",
timeStamp: 1513160947658
},
"key2": {
message: "message",
title: "title",
timeStamp: 1625904019915
},
"key3": {
message: "message",
title: "title",
timeStamp: 1626171405405
}
}
}
Here is the Firebase component:
Firebase.js
import { get, getDatabase, limitToFirst, limitToLast, onValue, orderByChild, query, ref } from 'firebase/database'
import firebase from 'firebase/compat/app'
import 'firebase/compat/database'
const config = { ... }
const db = getDatabase()
firebase.initializeApp(config)
export { db, get, limitToFirst, limitToLast, onValue, orderByChild, query, ref }
A component gets the first and last post:
FirstAndLast.js
import { db, get, limitToFirst, limitToLast, orderByChild, query, ref } from './Firebase'
const fetch = async () => {
// If I execute both lines, Listener.js snapshot.val() returns a null value
// If I remove one of these lines, Listener.js snapshot.val() returns the desired object
let snapshotFirst = await get(query(ref(db, 'posts'), orderByChild('timeStamp'), limitToFirst(1)))
let snapshotLast = await get(query(ref(db, 'posts'), orderByChild('timeStamp'), limitToLast(1)))
}
Another component listens to the key2 branch:
Listener.js
import { db, onValue, ref } from './Firebase'
onValue(ref(db, 'posts/key2'), snapshot => {
console.log(snapshot.val())
})
If I execute both components at the same time, Listener.js prints the desired object at first, but later on returns a null value as the final result.
If I remove (or comment) one of the snapshots at FirstAndLast.js, there aren't any issues.
It's anything wrong in combining limitToFirst() and limitToLast()?