0

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,
      })
    }

  }
}
Walter Monecke
  • 2,386
  • 1
  • 19
  • 52
  • https://blog.logrocket.com/react-hooks-with-firebase-firestore/ might help you – imjared Sep 08 '21 at 13:28
  • Does this answer your question? [Which react hook to use with firestore onsnapshot?](https://stackoverflow.com/questions/59944658/which-react-hook-to-use-with-firestore-onsnapshot) – imjared Sep 08 '21 at 13:29
  • @imjared I would need to refactor a lot and hooks are not an option. I would like to stick with my approach. – Walter Monecke Sep 08 '21 at 13:32

0 Answers0