Integrating Firestore Database — Ionic Part 5

Hey all! Last week, we added Firebase and 3 authorization pages (Login, Register and Forgot password), and boy, was that a really long post (Honestly, I got soooo tired halfway through).

This week we will integrate Firebase to all our existing methods.

The coding will be quite simple, as we have already integrated AngularFire into our app. The major changes will be made only to the back-end logic in the home.ts file, and one simple addition to the home.html to handle lists we get from Firestore.

Step 1 — The C in CRUD to Firestore

We’ll first start with adding functionality to the addTask() method. But first we need to import AngularFirestore to the home.ts and initialize it in the constructor, like so;

constructor(..public firestore: AngularFirestore) {}

As mentioned in the previous post, Firestore is not like its predecessor, it is not one big JSON structure. Instead, it works with something called documents. Each document is one uniquely JSON object that holds only one type of data, for example, the user object will only hold user data, such as their name, date of birth and other personal information, but not any other data.

Many documents of the same type make up a collection. And sometimes an object can have a collection of different objects inside it, and that’s what we are doing today; making a collection of task objects for each user.

If you can remember, in the previous post, we took the user’s uid, a unique ID that Firebase assigns all its users that sign up as the ID for the users’ JSON object. We will be requiring it heavily today as well, so the first thing to do is capture the uid from AngularFireAuth. As many methods will be using this value, it will be best to declare this variable outside the constructor, then initializing it inside ionViewDidLoad.

We put it in ionViewdidLoad(), because sometimes the user details from AngularFireAuth is not ready by the constructor. And since we will be accessing only that collection within the users' object, go ahead and grab that as well, similar to the register page. All this is added within the call to get the userId.

this.afAuth.authState.subscribe(user => {
if (user) {
this.userId = user.uid
this.fireStoreTaskList = this.firestore.doc<any>('users/' + this.userId).collection('tasks').valueChanges();
this.fireStoreList = this.firestore.doc<any>('users/' + this.userId).collection('tasks');
}
});

The reason why we have two lists is the fireStoreTaskList holds the list that we view, while the fireStoreList is the reference to the collection where we directly add the new tasks. The method valueChanges() returns an Observable List, which we can display in the view.

We can now use this reference anywhere in the page. Using it to add a task in the addTask method is very simple. There is a need to have a specific ID for each task, as we will require it when attempting to update the taskName, so we need to generate the ID and use the set() method of the firestore collection, to create a new task object, inside the if condition, replacing the previous code that pushes the task name into taskList.

let id = this.firestore.createId();
this.fireStoreList.doc(id).set({
id: id,
taskName: task
});

Step 2 — The R in CRUD in the App

Now to set up viewing the firestore list. The main part, getting the collection was done above. So the changes now need to be made to the home.html to view the fireStoreTaskList.

The first change is to be in the *ngFor, the name of the list. Since the list will be a response back by firebase, its asynchronous. The normal *ngFor, will cause errors. We need to add an async pipe as well, like so;

<ion-item *ngFor="let todo of fireStoreTaskList | async">

We no longer need to keep track of the index, as we will be using the task ID to either delete or update its value. And the second change is the value that we will view since todo will now be an object, we need to display todo.taskName, as that’s what we have named the task variable in the task object.

{{todo.taskName}}

And that’s it! Lets now have a look at both the app and Firestore, to see if it gets saved.

Create and Read tasks
Newly created task

It’s got saved!

There’s nothing much to it for the C and R in CRUD. Now to update then delete.

Step 3 — The U in CRUD to Firestore

Luckily, AngularFirestore has its own update function, which, given the documents’ ID as well as the values to be updated, can be done in one single line. But first, a small change in the home.html file, to allow this to happen. As said earlier, you don’t need the index of the task in the list to update or delete, but instead the document ID, which we have simply stored in the variable id of a task object.

Our first order of business is to send the tasks’ id to the method from the button, like so;

<button ion-button clear (click)="updateTask(todo.id)">

Move over to home.ts and replace the code in the handler of the alert to;

this.fireStoreList.doc(index).update({ taskName: data.editTask });

We first create a reference to the specific object that the user wishes to update using the doc() method, then sending the relevant data we wish to update into the update() method.

Now to see this functionality in action!

Update task name
Updated task name

This one works too!

Now onto the last change, delete.

Step 4 — The D in CRUD to Firestore

Deleting is just as easy (or easier, really) than updating.

You will again, need to pass the tasks’ ID onto the delete button;

<button ion-button clear (click)=”deleteTask(todo.id)”>

Again like for update, AngularFirestore has a function delete(), that is run on the reference of the document to be deleted, like so;

this.fireStoreList.doc(index).delete();

And now to watch the last functionality….

Delete task
Task deleted in Firestore

This one is functional too!

As you can see, the ‘Fold Clothes’ task with an ID of ‘NSskIVHEg4gKsT3U0xAV’ is no longer there, as it has been successfully deleted

There you have it! Firebase integrated into all the CRUD operations.

Tune in next week, for added bonuses!

Find the commit for this post, here.

P.S. Link to the last post!

Front End Developer at Switchd Ltd. | MSc in Computer Science @ QMUL (2022)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store