Skip to content

Instantly share code, notes, and snippets.

@JameelMukadam
Created February 22, 2018 12:44
Show Gist options
  • Save JameelMukadam/220a3a95c7bf3d73c16196f94a91ebb9 to your computer and use it in GitHub Desktop.
Save JameelMukadam/220a3a95c7bf3d73c16196f94a91ebb9 to your computer and use it in GitHub Desktop.
Realtime Programming with Firebase and Cloud Functions (in React Native - Ignite)

Firebase Cloud Functions

  1. npm install -g firebase-tools
  2. Run firebase login and login with your firebase account
  3. Select your project from the list shown to you
  4. Run firebase init functions which creates a functions directory
  5. Add your functions logic
  6. Run firebase deploy

All Done!

Main Code Snippets of index.js:

const functions = require('firebase-functions')
const admin = require('firebase-admin')

admin.initializeApp(functions.config().firebase)
var db = admin.database()

exports.sendCorrectPredictionNotifications = functions.database.ref('/referee-confirmed-events/{pushId}').onCreate((event) => {

let data = event.data.val()
let key = event.params.pushId

// return a specific value or do some asyn stuff by returning a promise
return new Promise((resolve, reject) => {

  // do some async stuff here 

})

})

Firebase Realtime coding example


How to subscribe to nodes on firebase

I'm assuming you have basic knowledge of React, Redux, Redux-Sagas and firebase.

The below snippet shows a basic firebase subscription function:

var starCountRef = firebase.database().ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
  updateStarCount(postElement, snapshot.val());
});

The below snippets allow you to subscribe to changes at a specific node and then fire off redux actions when a new event occurs at that node.


function channel (ref, event = 'child_added') {
  const channel = eventChannel(emit => {
    const callback = ref.on(
      event,
      dataSnapshot => emit({
        key: dataSnapshot.key,
        value: dataSnapshot.val()
      })
    )

    // Returns unsubscribe function
    return () => ref.off(event, callback)
  })

  return channel
}

^ This is the eventChannel function from Redux-Sagas which allows you to create a channel for your event listener which can then dispatch redux actions every time a specific event occurs.

function * startGameWatcher (gameID) {
 const gamesChannelsRef = firebase.database().ref(`games/${gameID}`)
 const game = channel(gamesChannelsRef, 'value')
 try {
   while (true) {
     const data = yield take(game)
     if (data.value) {
       yield put(GamesActions.updateGameRequest(data.value))
       if (data.value && data.value.status === 'ended') {
         game.close()
       }
     }
   }
 } catch (error) {
   game.close()
 } finally {
   if (yield cancelled()) {
     game.close()
   }
 }
}

^ This is the watcher generator function which starts the event listener which you created above and creates a continuous loop in a generator function which loops/steps every time there is an event from the listener you created above. It then takes that data and you are then able to dispatch new actions of your choice.


export function * watchGame ({ gameID }) {
  try {
    yield fork(startGameWatcher, gameID)
  } catch (err) {
    yield put(GamesActions.getGamesFailure(err))
  }
}

^ Lastly you need to kick off the watcher to run in the background so you use redux sagas fork event to run the watcher on a separate thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment