I am having a bit of trouble setting this up. I have a folder that deals with all the Db API, so that concerns are separated.
I have one function that opens a connection and gets realtime updates whenever a value in the Db changes (Firebase Firestore).
I call this "listener" function once and would like to keep receiving the real time values within the function that invokes the "listener" function.
Any ideas how I could achieve this?
This is my code:
// LISTENER FN
export const getConnectionRequestsFromDb = () => {
const uid = getUID()
const q = query(
collection(database, "inbox"),
where("uids", "array-contains-any", [uid]),
where("type", "==", "connectionRequest"),
limit(50)
)
const data = []
const unsubscribe = onSnapshot(q, (querySnapshot) => {
// Initially return an empty array, milliseconds later the actual values
querySnapshot.forEach((doc) => data.push(doc.data()))
})
const formattedData = convertDatesIntoJsTimestamps(data)
return [formattedData, null, unsubscribe]
}
// INVOKING FN
export const getConnectionRequests = () => {
return async (dispatch) => {
dispatch({ type: "CONNECTIONS_ACTIONS/GET_CONNECTIONS_REQUEST/pending" })
// I want to keep listening for realtime updates here and dispatch payloads accordingly
const [data, error, unsubscribe] = getConnectionRequestsFromDb()
if (data) {
return dispatch({
type: "CONNECTIONS_ACTIONS/GET_CONNECTIONS_REQUEST/fulfilled",
payload: data,
})
}
}
}