Lesson 26 Firebase Data

Mark Harder, 24 May 2019

Storing Your Data in Firestore

We want to store data and retrieve it in our app, so lets get started.

Here is a link to the Google Cloud firestore documentation we are going to use.
Open up the documentation and use it as a resource when you need to know more or have questions.

Here is a list of Firestore videos, please watch the first one before proceeding, and then come back and watch the others when you need to know more.

Watch This Video
What is a NoSQL Database? How is Cloud Firestore structured? | Get to Know Cloud Firestore #1 15:28 Minute video

  • Get to Know Cloud Firestore #1 NoSQL Database, Document Model.
    • 0:40 Relational Databases used strict structures, multiple tables joined by foreign keys. Traditionally SQL Relational databases are used to guarantee data integrity, structure and reduce redundancy.
    • 2:40 Firestore is NoSQL, schemaless.
    • 4:20 Code defensively, there is no guarantee that the data will be in a structure you expect.
    • 4:58 Separate calls for separate data, no SQL queries.
    • 8:02 The advantage is that NoSQL is fast and easy.
    • 8:44 NoSQL can scale automatically from small to large.
    • 9:55 Document model stores the data as hierarchical key:value pairs. This is known as JSON.
    • 10:25 Documents and Collections.
      • Documents are JSON key:value pairs know as fields.
        • maximum 1 MB of memory in size.
        • Documents can’t contain other documents.
      • Collections are collections of documents.
        • Collections can only contain strings.
      • Firestore Root can only contain collections.
    • 11:45 Drill down into your data format: firestore.collection(…).document(…)…
      • users/user_123/workouts/workout_abc Collection/Document/Collection/Document alternating

Recommended Video
How do queries work in Cloud Firestore? | Get to Know Cloud Firestore #2 16:03 Minute Video

  • Queries, How we get data out of firestore.

Highly Recommend Video
Maps, Arrays and Subcollections, Oh My! | Get to Know Cloud Firestore #4 12:49 Minute Video

  • Rules
    • Documents are limited to 1 MB or 20,000 fields.
    • Can’t retrieve less then one document.
    • Security rules are based around documents.

Suggested Video
How to Structure Your Data | Get to Know Cloud Firestore #5 14:27 Minute Video

Highly Recommend Video
Security Rules! 🔑 | Get to Know Cloud Firestore #6 22:38 Minute Video

Suggested Video
How Do I Paginate My Data? | Get to Know Cloud Firestore #7 10:15 Minute Video

  • How to split your data into many parts.

Suggested Video
How do Transactions Work? | Get to Know Cloud Firestore #8 16:09 Minute Video

  • Atomic batch operations

Creating a CRUD app

What is CRUD?

  • C: Create Data
  • R: Read Data
  • U: Update Data
  • D: Delete Data

Our application is going to demonstrate all of these operations. You can find the complete project code (except the file firestore.js) in github.com/mhintegrity/Lesson 26

Commands to start Building our App.

In past lessons we have covered most of these command, but I will quickly list them in order.

Lets create our new project using the Vue CLI.

vue create vue-awards

Follow steps from Lesson 23 Vue Router to create the project

In the command line of our project we need to add firebase as a library

$ npm install – save firebase

More details in Lesson 24 Firebase Deploy

Initiate this project, to start with we are going to only use the Hosting feature, so only choose hosting.

$ firebase init

Create a Firestore database named awards

  1. In your firebase console, select/click Database
  2. Make sure Cloud Firestore is selected in the dropdown, not Realtime Database
  3. Select/click Add collection to start a collection
  4. Name the collection awards

image

  1. Choose Cloud Firestore
  2. Example added document

Firestore Add Collection

Lets add some fields to our document.

  1. First field name is title type string
  2. Value is High Kick
  3. Next add a field detail type string value Kick over your head
  4. Next add a field completed type boolean value false
  5. Next add a field createdAt type timestamp

In the next section we will update our code to add items to this collection using the app, not here in the console.

Setup a new project in the Firebase console and add the details for connecting to firebase to a new local file firebase.js, look in the settings for the api keys.

addFirebase

To our project we are going to add the firebase config.

firebasejs

  1. A file at the base level named firebase.js, in lesson 24 we named it firebaseConfig.js.
  2. Import all functions from the firebase library using *
  3. We are going to export a Collection of data we create named awards. See how we choose to call the top level collection we created: firebase.firestore().collection('awards');

Building our views

Make a local clone of my project (in another directory) so that you can look at the code in one instance of VS Code and work on your own project in another.

git clone https://github.com/mhintegrity/Lesson26.git

First we need to load our app with a very simple main.js file.

image

  • The hard work of loading firebase is being done in firebase.js
  • If you use authentication this will need to change to follow the pattern of Lesson 25.

Our App.vue is also very simple with only links two our two views

appvue

We have placed the main details in Home.vue view

First lets see what the page will look like when running.

add

  • The top card is always on the page.
  • Below we find a list of cards displaying data from the database.
  • The top card is titled New Award and has an Add button for when you have finished entering a title and details. This covers C in CRUD.
  • The list of cards holding saved awards each have an Edit and Delete button. This covers U and D in CRUD.
  • The list of cards coming from firestore covers R in CRUD.

Lets look at the code for Home.vue

homevue

  1. Title at the top of the Home.vue view.
  2. Title of the static card at the top of the screen, which is used to add a new award.
  3. Input text control where the user enters a new title. We link the user input to a data variable named newAwardTitle
  4. Input text control where the user enters the Detail. We link the user input to a data variable named newAwardDetail
  5. Our add button calls a method named addAward
  6. We use a UL User List HTML control to list our cards. All details are contained in a component named AwardListItem.vue
  7. Here is the import of the AwardCard component.
  8. Look at CSS to see how we display our cards.

Code to Create Data in Cloud Firestore

Clicking the Add button calls the method addAward

Add code

  1. Here is the JavaScript function that is called when the Add button is clicked.
  2. First we do an if check to make sure there is a title with a length of 1+, then we call the object awardsCollection which we imported using import { awardsCollection } from "@/firebase";. This is the collection of documents Firestore provides with the firebase library.
    1. .add({}) is the library function to add a new document to our collection. Using { title: "string or string variable" } format we create a JavaScript object, which is also JSON and can be stored in our Firestore Document.
    2. You can see more details at this google firebase page Adding Data to Cloud Firestore
    3. .then() is called when we save successfully to Cloud Firestore.
    4. .catch() is called when there is an error trying to save to Cloud Firestore.
    5. Next we reset our variables which are linked to the screen input text boxes. We want the user to be able to enter another item.
    6. We call the method refreshData which performs the Read of documents from our collection in Cloud Firestore.

Code to Read Data in Cloud Firestore

There are multiple locations where we read our collection from Cloud Firestore using the method refreshData.
The created() method is called when the app loads the Home screen, so this is the first time we call the method refreshData.

Read Data

  1. The refreshData method represents the R in CRUD. We are going to read a collection of documents that we used to display cards on the screen.
    1. Here is a link to the Google Firebase documentation Getting Data with Cloud Firestore
  2. We call the .get() method on our firebase library.
    1. The called to .then() is asynchronous, which means the code makes the call to Firestore and waits in the background till it gets a response back.
    2. querySnapshot is the variable of our function that holds the returned collection of data.
    3. We need to reset our local array that is used to display the data on our screen. The awards variable is in data, see 7 at line 59.
  3. The Javascript method forEach will perform a block of code for each items in our returned array (collection) of objects (documents).
  4. This is a commented out line which will print the document id and fields in the console.
  5. First we create a new variable named data to store the fields from our doc using the method .data()
  6. Now we create a new object which is our award and add it to our array this.awards using the JavaScript array method push
  7. empty awards data variable that is used to display our awards in cards. See the next code which shows how award-card is used.

display

  1. We have a list < ul > that creates an instance of the award-card component for each item in the this.awards array.
    1. v-for creates an instance of award-card for each item in the array this.awards
    2. v-bind:key links the id field to our component instance.
    3. v-bind:award passes in the item from the array this.awards into the component.
    4. v-on:deleteAward catch’s the $emit coming from the component award-card, and calls the method deleteAward. If you look in the component you will see that this is called when the user clicks the delete button.
  2. In the data section is where we define the array this.awards
  3. Here is where we add the objects based on the document collection returned from Firestore.

Code to Delete Data in Cloud Firestore

When the user clicks Delete on an award card, we emit an event from the component up to App which deletes the document from Cloud Firestore.
Lets look inside the award-card component. The file is named AwardListItem.vue.

component

  1. The award object which contains our data fields and an id is passed into the component and stored in props as award.
  2. We are using a vue conditional rendering directive to switch our controls between displaying text for our title and a text input box when in edit mode. We are using the editMode property of the award data variable to choose between edit and view mode.
  3. v-else will display the text in a label when award.editMode is false. Notice that the data type for editMode is a boolean that starts out as false.
  4. When v-else we see the title label and two buttons, Edit and Delete. When True we instead get the input text box and the buttons Save and Undo.
  5. The delete button calls this method deleteAward and this method does an $emit to send a message out of award-card back up to Home.vue.

delete code

  1. We can see that the $emit command calls this method deleteAward and passing in our variable award.
  2. Just like our add we call a firebase method on our collection called delete. Notice that we first call .doc and pass in our id (key) which is a call to select our document based on our key/id and then do the delete.

Read more about delete at Deleting Data from Cloud Firestore

Code to Update Data in Cloud Firestore

In the AwardListItem.vue you can see the code that is used to edit an award, and then call updateAward in Home.vue.

update

  • Line 54 is a function that is called when the user clicks the save button.
  • Line 55, 56 set the award prop variable title and detail to be the values the user has entered into the input text boxes.
  • Line 57 send a message up out of this component back up to Home.vue, so that it can call the update method.
  • Line 58 set the component to not be in edit mode.

update 2

  1. v-on:updateAward will capture the $emit from inside the component and then call the local method updateAward and pass in the award object from the v-for command on line 35.
  2. We start will the awardsCollection and use the .doc method, like we did in delete to select our document out of our collection.
  3. Next we call the method update which accepts an object with 1 + fields. Only the fields passed in will be updated.

Here is what the screen looks like when

edit

  • Card # 1 shows a card in Edit Mode. We have the choice to undo our edit or Save it.
  • Card # 2 shows a card not in Edit Mode. We can use the buttons to enter Edit mode or delete the card.

No More Assignments

Work on your Project.

  1. Make sure to check-in your code to Github for your project every time you complete some work.
  2. After testing your code locally, deploy to Firebase.
  3. Ask other student in the class, and over Slack to try out what you have deployed to Firebase.