I have two listeners - one for the user's profile
and one for the rooms
the user is in; the uids of the rooms
are stored in an array on the profile
, i.e. the query for the second listener depends on data from the first.
It looks like this (simplified):
// profile listener
onSnapshot(profileRef, (snapshot) => setProfile(snapshot.doc.data())
// rooms listener
const roomsQuery = query(
collection(db, "rooms")
where("uid", "in", profile.roomsList)
)
onSnapshot(roomsQuery, (snapshot) => setRooms(snapshot.docs)
When the user is added to a new room
, the profile
updates with the new roomsList
. But the rooms
snapshot doesn't update - presumably because the query can't be updated dynamically.
Question
So, is there a way of updating the listener's query (i.e. keeping the same listener), or do I have to unsubscribe from the existing listener and re-subscribe with the new query every time profile
is updated?
Versions
Using the new V9 of the Javascript sdk
CodePudding user response:
Firestore queries are immutable, so there's no way to change the condition once the query has been created. You'll indeed have to attach a listener to a new query to get the updates roomsList
. If you enable offline persistence though, the overlapping documents between the queries will be read from the local cache.
Also see: How to constantly update query for Firebase Realtime Database with LiveData and ViewModel in Android