Integrating Ionic Vue Application with Firebase — Firestore CRUD operations
Tags: firestore, ionic, vue, firebase
Published: 2022-06-29 16:10:54

---
title: Integrating Ionic Vue Application with Firebase — Firestore CRUD operations
published: true
date: 2022-06-25 06:52:45 UTC
tags: firestore,ionic,vue,firebase
canonical_url: https://enappd.com/blog/ionic-vue-with-firebase-firestore/194/
---

### Integrating Ionic Vue Application with Firebase — Firestore CRUD operations

![](https://cdn-images-1.medium.com/max/1024/1*8HepPqrsdvtFHopkRe9VSA.png)

In this tutorial, we will learn how we can integrate the Ionic Vue application with Firebase firestore and use basic database operations. Firebase is one of the best options to opt for when dealing with a small number of users (for unpaid versions). You can add a lot of things using Firebase like push notifications, database providers, authentication methods, Firebase functions, and many more.

### What is Ionic?

**Ionic** is a complete open-source SDK for hybrid mobile app development created by Max Lynch, Ben Sperry, and Adam Bradley of Drifty Co. in 2013. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices.

We can use Cordova or Capacitor to build these awesome apps and have native functionalities. With this, we get some amazing native plugins to use like Image cropper, Camera, and many more.

### Capacitor — How is it different from Cordova?

This section is relevant to only those who have been working with Ionic / Cordova for some time. Cordova has been the only choice available for Ionic app developers for quite some time. Cordova helps build an Ionic web app into a device installable app.

> **_Capacitor is very similar to Cordova, but with some key differences in the app workflow_**

Here are the differences between Cordova and Capacitor (You’ll appreciate these only if you have been using Cordova earlier, otherwise you can just skip)

1. Capacitor considers each platform project a _source asset_ instead of a _build time asset_. That means Capacitor wants you to keep the platform source code in the repository, unlike Cordova which always assumes that you will generate the platform code on build time
2. Because of the above, Capacitor does not use config.xml a similar custom configuration for platform settings. Instead, configuration changes are made by editing AndroidManifest.xml for Android and Info.plist for Xcode
3. Capacitor does not “run on device” or emulate through the command line. Instead, such operations occur through the platform-specific IDE. So you cannot run an Ionic-capacitor app using a command like ionic run ios . You will have to run iOS apps using Xcode, and Android apps using Android studio
4. Since platform code is not a _source asset,_ you can directly change the native code using Xcode or Android Studio. This gives more flexibility to developers

In essence, Capacitor is like a fresh, more flexible version of Cordova.

### What is Vue?

Vue is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with [modern tooling](https://vuejs.org/v2/guide/single-file-components.html) and [supporting libraries](https://github.com/vuejs/awesome-vue#components--libraries). (If you want to know more about Ionic Vue then read Introduction to Ionic Vue Blog)

### Firebase 🔥

If you already know what is firebase — SKIP this section.

Firebase is a popular Backend-as-a-Service (BaaS) platform. It started as a [YC11 startup](http://blog.ycombinator.com/firebase-yc-s11-raises-5-dollars-dot-6m-series-a-from-union-square-ventures-and-flybridge) and grew up into a next-generation app-development platform on Google Cloud Platform. It is getting popular by the day because of the ease of integration and the variety of functionalities available on it.

A lot of quick integrations are available with Firebase. Some of these are listed below:

- Real-time Database 🗄️
- Firestore Database
- Email Authentication 📧
- Social logins📱
- In-app messages
- Push notifications
- Analytics 📊
- Crashlytics 💥
- Remote config

Firebase is quickly growing to become the most popular mobile app back-end platform. And now we got an easy way to handle the firebase project by using the **emulator**. You can be running a firebase project in the localhost rather than spending bucks on creating a cloud instance, It makes the work easy and clean. And If you want to know more about Firebase Emulator you can to [Firebase Emulator Blog](https://enappd.com/blog/how-to-use-firebase-emulators-with-ionic-angular-applications/163/).

### Connect the Ionic Vue app with Firebase

In this section, we will go through three steps :

1. Set up the firebase project from the firebase console
2. Create Ionic VueProject (integrate it with the firebase)
3. At last, perform the CRUD operation in Cloud Firestore.

#### **Step — 1. Setting up firebase project:-**

Firstly we have to create a new Firebase project in [firebase Console](https://console.firebase.google.com/), then just click on **_Add Project_** and enter project details.

![](https://cdn-images-1.medium.com/max/914/1*fpCWNXgmZJh-X_JwWbRolQ.png)

Now once the firebase project is created then go to cloud firestore and create a firestore database. And keep in mind you should create the firestore database in test mode **(Test mode enables the read, write, update and delete permission for everybody)**

![](https://cdn-images-1.medium.com/max/285/1*kZDN6bsEs_Yix3Hdpzqadg.png)

Now we are ready to integrate the Firebase with the Ionic Vue, But we have to copy the Firebase Project Config so that we can use that in the Vue Project. To copy the config just go to _project settings_ and copy the firebase project. **(We just want project Id)**

![](https://cdn-images-1.medium.com/max/1024/1*kci9NM0iQsdzv4E0n0oF4Q.png)

#### 2. Creating a new Ionic Vue Project and Integrating it with the Firebase project

You can get the completed source code of the Ionic Vue Application [HERE](https://github.com/enappd/ionic-vue-firebase). And before Integrating we have to create a new Ionic Vue Project, To create a new Ionic project follow the below steps:-

To create an Ionic Vue project, you have to follow the same steps as for Ionic react or angular. But keep in mind that you have the latest version of Ionic-cli as Vue is updated in the newer version (Ionic-cli V6.12.2 — At the time of blog). You can update ionic-cli using the below command:-

```
$ npm install -g @ionic/cli
```

Once the update is complete, Now we can create a new Ionic + Vue application. To create you can run the below command:-

```
$ ionic start firebaseVue blank --type vue
```

The above command contains the **name of the project** after that you can pass **template** types like ‘blank’, ‘tabs’ to choose the layout of the Ionic Vue project. And at last, we have given **vue** as the **type of framework** to use. The command will take some time to create the project, and after that, a new project will be created in the working directory. We are done with creating a new Ionic Vue project, and now we will integrate it with Firebase.

To integrate Ionic Vue with firebase, we have to install firebase in our project using the below command :

```
npm install firebase
```

Once the firebase is installed in Ionic Vue Project, we have to create the **firebase-service.ts** file in the **src** directory of the Vue Project. **src** folder structure will look like this:-

![](https://cdn-images-1.medium.com/max/216/1*EZ93ClRK0l7kFxlvM5QyUw.jpeg)

**firebase-service.ts** will contain all of the logic related to firebase like initialization of the firebase project, query related logic. First, we will look at the initialization of the Firebase project in the Ionic Vue project.

{% gist https://gist.github.com/vaibhavgehani/ef0e9d6d8a04a424590a60aa006ba842 %}

In the above code, we first import the installed firebase by using the import statement in **firebase-service.ts**

```
import firebase from "firebase/app";

import "firebase/firestore";
```

Now we will use the firebase instance to initialize the firebase project using its **initializeApp** () method. To initialize the firebase project, we have to use the **projectID** (which we have copied from Firebase Config).

You will also need Firebase CLI to use some of the Firebase commands. If you want to know more about how to install **firebase/cli** you can go [here](https://firebase.google.com/docs/cli) and check the requirements for your OS.

You must be logged in to Firebase. (If not use the _firebase login_ command to login into your terminal, this command will work after installing firebase/cli)

```
_const_ db = firebase.initializeApp({
   projectId: ' **Your firebase projectID**'
}).firestore();
```

Now DB instance is created, we will use this DB instance to use the collections and docs in the cloud firestore. **firebase-service.ts** exports the function that contains the sub-functions which perform the query-related logic. We have taken the example of READING the data from firestore collection. We will explain more in the next section.

```
_const_ readFromFirebase = async (_collectionName_) _=>_ {
  _const_ FirebaseCollection = db.collection(collectionName);
  _const_ querySnapshot = await FirebaseCollection.get();
  _const_ result = querySnapshot.docs.map((_doc_: _any_) _=>_ {
  return {...doc.data()}
});
  return result;
};
```

In this code, **db.collection(collectionName)** will create a instance of the collection/table. And we will use that instance to read the data from the table using **_get_** () method of the instance.

#### 3. Adding CRUD operation using Cloud Firestore

We have added the **firebase-service.ts** file to the Vue project and initialized the firebase project. Now we will create the views using which we will perform the CRUD operations.

1. **Create Operation:-**

To perform the CREATE operation, we will build a simple UI that will take the input as the _username_ and _password_. The given input will be saved into the **users** collection in the cloud firestore. We will use the **Create.vue** file to perform the Create Operation.

![](https://cdn-images-1.medium.com/max/215/1*Of8D-tsINXcUlESpUDs6pg.jpeg)

Once you create the **Create.vue** file, we will add the UI and related Logic in the file. In the below code, we call the firebase-service **createOperation() method** _[Line 68 in below code]_ with the User Object. The code is given as below, we will explain the firbase CRUD part later :

{% gist https://gist.github.com/vaibhavgehani/292802c5a5981ad7ebdc63659769e3d9 %}

Above code UI will render like:-

![](https://cdn-images-1.medium.com/max/301/1*a21aV_z15Hqww-4yb2JzLA.jpeg)

In the above code, we have created the two input fields (for _username_ and _password_) and two buttons (for Saving Data and getting the List of Users). To perform the Create Operation, we have defined **createOperation()**

```
async createOperation() {
  _const_ userObject = {
    username: this.username,
    password: this.password
   }
  _console_.log('Data', this.username, this.password);
  _const_ UsersData = await firebaseService().createOperation('Users',
  userObject);
},
```

simply call the create operation() function defined in **firebase-service.ts** file _(Created earlier in the blog)_ with **collectionName** and **userData** as the argument _[Line 68 in above code]_. And in reading Operation (View Data Button) _[Line 29 in above code]_ navigate to ** Read.vue**

**2. Read Operation:-**

To perform the Read operation, add the **Read.vue** file and show the list of users with update and delete buttons. Below is the Code for **Read.vue** file which consists of the UI rendering and Read Operation related Logic.

{% gist https://gist.github.com/vaibhavgehani/05afb2397b02a1f7571b68c8b1e2133d %}

The above Code will render UI like this:-

![](https://cdn-images-1.medium.com/max/298/1*OTX-4RKcftp0YMkJZwD-IA.jpeg)

The above code consists of **created** () method _[Line 36 in above code]_ which is called as soon as the **Read.vue** page is loaded into the DOM. So in this method, we will call the firebase-service’s method to GET/READ all the users in the **Users** collection.

```
created() {
  _const_ usersList = firebaseService().readOperation('Users');
  usersList.then((_data_: _any_) _=>_ {
  this.usersList = data;
  })
}
```

Now we can render the list of users (i.e. this. **usersList** ) using the ion-list, and will use the “ **v-for** ” prop _[Line 10 in above code]_ to render it.

```
<ion-list>
  <ion-item v-for="(item, index) in usersList" :key="index">
    {{ item.username }}
    <ion-button slot="end" @click="updateOperation(item, index)">update</ion-button>
    <ion-button slot="end" @click="deleteOperation(item, index)">Delete</ion-button>
  </ion-item>
</ion-list>
```

**3. Delete and Update Operation:-**

And for delete operation, will call the **_deleteOperation_** () method (defined in firebase-service.ts) and pass in the **collectionName** and users _username_ as the arguments.

```
deleteOperation(_item_: _any_, _index_: _any_) {
  _console_.log(item);
  this.usersList.splice(index, 1);
  firebaseService().deleteOperation('Users', item.username);
}
```

For Update Operation method _[Line 50 in read.vue file]_, we just navigate to the Update.Vue page with users' username as the **params** [passing {id: data.username}] using the router capability.

```
async updateOperation(_item_: _any_, _index_: _any_) {
  _const_ data: _any_ = await firebaseService().findIdForDoc('Users', item.username);
  this.$router.push({name: 'Update', params: {id: data.username}})
}
```

**4. Update Operation:-**

To perform the update operation, we just create **Update.vue** file. And will add the updated page UI and query-related logic to it. Below is the code for the **Update.Vue** file.

{% gist https://gist.github.com/vaibhavgehani/c7479e775c7db146d8ba4e6c0f26fa61 %}

The above code will render like this :-

![](https://cdn-images-1.medium.com/max/302/1*L9ONaNUOwHdgg9Ez9cpk_A.jpeg)

We have passed the user's username from the **Read.vue** file _[Line 54 in read.vue file]_, And will get that in Update.Vue file using the props option. Now we can refer username as **this.id** in the entire code.

```
props: ['id']
```

Now to perform the update operation we define the **_updateOperation_** () method. And inside this function will call the **_updateOperation_** () method (defined in firebase-service file) and pass in the **collectionName** and updated user data as the argument.

```
async updateOperation() {
  _const_ updated = await firebaseService().updateOperation('Users', this.usersData);
  this.router.push('/read');
}
```

Now we are done with all of the CRUD operations performed in Firebase collections. But to make this code work we have to change the router file defined in **_router/index.ts_**

{% gist https://gist.github.com/vaibhavgehani/6899cfa117665d6ec3ba1359a8572b6a %}

The above code will handle all the routes present in the Ionic Vue application, you can change your **index.ts** file to this code. We have defined many firebase-service.ts functions on different pages. Below is the complete code for the **firebase-service.ts** file.

{% gist https://gist.github.com/vaibhavgehani/667831459a83a60ade009ac86fd2ee2c %}

### Conclusion

In this tutorial, we have learned how to integrate the Ionic Vue application with Firebase cloud Firestore and along with it learned about a few basics of the Ionic Vue App. You can get the Source Code of this Ionic Vue Application [HERE](https://github.com/enappd/ionic-vue-firebase). And if you want to know more about any of the technology or feature you can visit [Enappd Blogs](https://enappd.com/blog/).

### Next Steps

If you liked this blog, you will also find the following Ionic blogs interesting and helpful. Feel free to ask any questions in the comment section

- Ionic Payment Gateways — [Stripe](https://enappd.com/blog/ionic-4-stripe-payment-integration-with-firebase-for-apps-and-pwa/17) | [PayPal](https://enappd.com/blog/ionic-4-paypal-payment-integration-for-apps-and-pwa/16) | [Apple Pay](https://enappd.com/blog/how-to-integrate-apple-pay-in-ionic-4-apps/21) | [RazorPay](https://enappd.com/blog/how-to-integrate-razorpay-in-ionic-4-apps-and-pwa/20)
- Ionic Charts with — [Google Charts](https://enappd.com/blog/ionic-4-charts-using-google-charts/66)| [HighCharts](https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-3/60) | [d3.js](https://enappd.com/blog/adding-charts-in-ionic-4-apps-and-pwa-part-2/54) | [Chart.js](https://enappd.com/blog/charts-in-ionic-4-apps-and-pwa-part-1/52)
- Ionic Social Logins — [Facebook](https://enappd.com/blog/facebook-login-in-ionic-4-apps-using-firebase/25) | [Google](https://enappd.com/blog/google-login-in-ionic-4-apps-using-firebase/39) | [Twitter](https://enappd.com/blog/twitter-login-in-ionic-4-apps-using-firebase/24)
- Ionic Authentications — [Via Email](https://enappd.com/blog/email-authentication-with-firebase-in-ionic-4/38) | [Anonymous](https://enappd.com/blog/firebase-anonymous-login-in-ionic-4/37)
- Ionic Features — [Geolocation](https://enappd.com/blog/using-geolocation-geocoding-and-reverse-geocoding-in-ionic-4/45) | [QR Code reader](https://enappd.com/blog/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4/9)| [Pedometer](https://enappd.com/blog/best-fitness-plugins-for-ionic-4-how-to-use-pedometer/15)
- Media in Ionic — [Audio](https://enappd.com/blog/spotify-like-music-in-ionic-4-apps/48) | [Video](https://enappd.com/blog/adding-video-player-in-ionic-4-app/64) | [Image Picker](https://enappd.com/blog/image-picker-in-ionic-4-app/67) | [Image Cropper](https://enappd.com/blog/how-to-add-image-cropper-in-ionic-4-app/68)
- Ionic Essentials — [Native Storage](https://enappd.com/blog/ionic-4-save-and-retrieve-data-locally-on-device/59) | [Translations](https://enappd.com/blog/how-to-translate-in-ionic-4-globalization-internationalization-and-localization/11) | [RTL](https://enappd.com/blog/rtl-right-to-left-use-in-ionic-4/50)
- Ionic messaging — [Firebase Push](https://enappd.com/blog/implement-ionic-4-firebase-push/34) | [Reading SMS](https://enappd.com/blog/automatically-read-sms-in-ionic-4-apps/42)
- Ionic with Firebase — [Basics](https://enappd.com/blog/how-to-integrate-firebase-in-ionic-4-apps/23) | [Hosting and DB](https://enappd.com/blog/firebase-with-ionic-4-hosting-auth-and-db-connection/58) | [Cloud functions](https://enappd.com/blog/firebase-cloud-functions-in-ionic-4-complete-guide/32)

### Ionic React Full App with Capacitor

If you need a base to start your next Ionic 5 React Capacitor app, you can make your next awesome app using [Ionic 5 React Full App in Capacitor](https://store.enappd.com/product/ionic-react-full-app-capacitor/)

![Ionic 5 React Full App in Capacitor from Enappd](https://cdn-images-1.medium.com/max/760/1*G3yOFVX4oABx9MhUy-3kng.png)

### Ionic Capacitor Full App (Angular)

If you need a base to start your next Angular **Capacitor app** , you can make your next awesome app using [Capacitor Full App](https://store.enappd.com/product/capacitor-full-app-with-ionic-angular/)

![Capacitor Full App with huge number of layouts and features](https://cdn-images-1.medium.com/max/736/0*UwSHcofTMStMnzAX.png)

### Ionic Full App (Angular and Cordova)

If you need a base to start your next Ionic 5 app, you can make your next awesome app using [Ionic 5 Full App](https://store.enappd.com/product/ionic-full-app)

![Ionic Full App with huge number of layouts and features](https://cdn-images-1.medium.com/max/700/0*1ArpKyhiDHZnevwB.jpeg)


* * *