score:0

Accepted answer
/**
 * @description
 * this function adds a firebase socket listener. The listener will fire
 * an action every time the value is changed.
 *
 * @param {String} document - firebase document name (can be a path)
 * @param {String} key - uid for an item in the firebase
 * @returns {Function}
 */
const fetchReference = (document, key = null) => (dispatch, getState) => {
  const documentReference = firebase.database().ref(document);
  const reference = key ? documentReference.child(key) : documentReference;

  reference.on('value', (snapshot) => {
    const state = getState();
    const firebaseDocument = state.firebase[document];
    const snapshotValue = snapshot.val();

    if (
      firebaseDocument
      && firebaseDocument[key]
      && (JSON.stringify(firebaseDocument[key]) === JSON.stringify(snapshotValue))
    ) {
      return;
    }

    dispatch({
      type: FETCH_FIREBASE_REFERENCE,
      payload: snapshotValue,
      document,
      key,
    });
  });
};

Related Query

More Query from same tag