Start codelab

Codelab Flow

What you will learn

L Last updated on 19/07/18 F Firebase Cloud Firestore

In this codelab, we're going to learn how to add Firebase to your web app and serve content from the Firebase Cloud Firestore and make your web app work offline as well.

Get Source code

You will download a ZIP file containing several example resources files and the starting work folder. Unzip the folder and open the work directory with say code editor. We prefer Visual Studio Code.

Setting up

We shall be using Firebase in this codelab. Make sure you install firebase tools as in this guide here before we begin. Just install and leave it there.

Create a Cloud Firestore project

Open the Firebase Console and create a new project. In the Database section, click the Get Started button for Cloud Firestore.

Select a starting mode for your Cloud Firestore Security Rules

To get started with the Web, select test mode and click Enable. Test Mode is good for getting started with the mobile and web client libraries, but allows anyone to read and overwrite your data. Make sure to see how to secure in cloud firestore.

Hands on

The default index.html page in our work folder is already set ready to configure our project for Firebase use. At the bottom of our page, we have added the Firebase and Cloud Firestore libraries we need to set up.

We also have service-worker.js in our project that allows us to add progressive web app offline features. Learn more about the service worker and its features.

Adding Firebase to our Web app

Go to your firebase console here and select your project. Click Settings icon on the top left side just beside Project Overview and select Project Settings. Scroll down the view and click Add Firebase to your web app icon. Do not close the tab.

Make sure you are in the work folder. Open the app folder. Here we have main.css and faqbeta.js which styles up our web app and empty javascript files; app.js, firestore.js and data.js. We are going to add some code to them.

Open firestore.js and copy the code snippet below to it. Replace the firebase data values with the ones in the firebase console tab you left open above.

  // Initialize Firebase
  let config = {
    apiKey: "apiKey",
    authDomain: "projectId.firebaseapp.com",
    databaseURL: "https://databaseName.firebaseio.com",
    projectId: "projectId",
    storageBucket: "bucket.appspot.com",
    messagingSenderId: "messagingSenderId"
  };

  firebase.initializeApp(config);
  let firestore = firebase.firestore();
  console.log("Cloud Firestores Loaded")

  var db = firebase.firestore();

  const timestamps = firebase.firestore();
  const settings = {
    timestampsInSnapshots: true
  };
  firestore.settings(settings);

Enable offline data

This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline.

This code snippet does that for us. Copy and add it below the code above in firestore.js file

This code snippet does that for us. Copy and add it below the code above in firestore.js file

  // Enable offline capabilities
  firebase.firestore().enablePersistence()
    .then(function() {
        // Initialize Cloud Firestore through firebase
        var db = firebase.firestore();
    })
    .catch(function(err) {
        if (err.code == 'failed-precondition') {
            // Multiple tabs open, persistence can only be enabled in one tab at a a time.

        } else if (err.code == 'unimplemented') {
            // The current browser does not support all of the
            // features required to enable persistence
            // ...
        }
    });

Read firestore data from database in the meetups collection

The code below allows us to read firestore data from our database in the meetups collection created; Add it below the code above

NOTE The next_title.innerText code for instance, gets the next meetup title value and passes it to our data.js which then is displayed into our web app in the paragraph element; i.e

<p class="faqbeta_accordion" id="next_title"></p>
This code snippet does that for us. Copy and add it below the code above in firestore.js file

  var docRef = db.collection('meetups').doc('categ');
// Update the timestamp field with the value from the server
var updateTimestamp = docRef.update({
    timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
console.log(updateTimestamp)

// Read firestore data from database in the meetups collection
db.collection("meetups").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} =>`, doc.data());
        const meetups = doc.data();
        next_title.innerText = meetups.next_title;
        next_desc.innerText = meetups.next_desc;
        recent_title.innerText = meetups.recent_title;
        recent_desc.innerText = meetups.recent_desc;
    });
});

Create "meetups" document in our database

Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document.

This code creates a new document in our project's database and poulates it with our Meetups data; The Meetups' titles and descriptions.

In the app folder, open data.js file and copy the code snippet below to it.

  // Create meetups document
  var docRef = db.collection("meetups").doc("categ");
  docRef.set({
    next_title: "Next '18 Extended 2018",
    next_desc: "Next ’18 is a three day global exhibition of inspiration, innovation, and education where we learn from one another how the cloud can transform how we work and power everyone’s successes.",
    recent_title: "Google IO Extended Eldoret 2018",
    recent_desc: "I/O Extended events help developers from around the world take part in the I/O experience from wherever they are. We had Talks, Hands-on sessions and I/O 18 Recap viewing",
    timestamp: ""
  })

  .then(function() {
    console.log("Document successfully created!");

  });

Display data into our web app

In the app folder again, open app.js and add the code snippet below to it.

Explanation : The next_title.innerText code in stage 3 for gets the next meetup title value and passes it to our data.js which then is displayed into our web app in the paragraph element; i.e our paragraph element has its id as next_title and we use this id to display the data into our paragraph element.

<p class="faqbeta_accordion" id="next_title"></p>
In the app folder, open app.js file and copy the code snippet below to it.

  /**
  * Copyright 2018 PWAFire.Org. All Rights Reserved.
  */
  // Display data into our web app
  const next_title=document.querySelector("#next_title");
  const next_desc=document.querySelector("#next_desc");
  const recent_title=document.querySelector("#recent_title");
  const recent_desc=document.querySelector("#recent_desc");

Firebase Hosting

We are done! Let's now deploy our cloud firestore web app to firebase ! Follow this guide here to deploy our web app. Go offline and refresh your web app. The web app data is still available while offline.

If you are using Chrome browser, open Dev Tools and while in the Application panel, select Service Worker and enable offline. Refresh your web app. Celebrate! Aren't you a nerd already?

What's next?

You got any bug? report it here for support. You want to contribute? Create your feature here

Support

Donate a Star and Contribute in any way. Be sure to follow us on Twitter.

License

Copyright PWA Fire, 2018. Licensed under an MIT License.

FORK ON GITHUB