Skip to content Skip to sidebar Skip to footer

Quasar 2 & Firebase Cloud Firestore (with Vue 3 & Pinia)

Quasar 2 & Firebase Cloud Firestore (with Vue 3 & Pinia)

The combination of Quasar Framework, Firebase Cloud Firestore, Vue 3, and Pinia provides a modern, powerful, and streamlined approach to building web applications. Quasar 2 allows developers to build cross-platform applications with Vue.js at its core, while Firebase Cloud Firestore serves as a serverless, NoSQL cloud database, offering real-time syncing and seamless scaling. Pinia, the new state management library designed for Vue 3, offers a simpler and more intuitive API compared to Vuex, making it easier to manage state in complex applications. 

Buy Now

Let’s explore how these technologies work together and how to set up a project that integrates all these components.

Setting Up the Project

To start, we need to install Quasar CLI, which will help us scaffold a Quasar project. Once the project is initialized, we'll integrate Firebase Cloud Firestore and Pinia.

Step 1: Install Quasar CLI

First, install the Quasar CLI globally:

bash
npm install -g @quasar/cli

Next, initialize a Quasar project by running:

bash
quasar create my-app

During the setup process, you'll be asked to choose some options like CSS preprocessor, ESLint configurations, and more. Once you've configured your project, navigate into the project directory:

bash
cd my-app

Step 2: Install Firebase SDK

To integrate Firebase, install the Firebase SDK and the Firebase tools required for Firestore. Run the following command inside your project directory:

bash
npm install firebase

Step 3: Set Up Firebase in Your Project

Now, let’s create a Firebase project. Go to the Firebase Console, create a new project, and enable Cloud Firestore from the Database section.

Once your Firebase project is set up, click the Web icon to add a web app, then follow the instructions to get your Firebase configuration object, which will look something like this:

javascript
const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT_ID.firebaseapp.com", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_PROJECT_ID.appspot.com", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" };

Step 4: Initialize Firebase in Quasar

In your Quasar project, navigate to src/boot/ and create a new file called firebase.js. This will be where we initialize Firebase. In firebase.js, add the following code:

javascript
import { initializeApp } from 'firebase/app'; import { getFirestore } from 'firebase/firestore'; const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_PROJECT_ID.firebaseapp.com", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_PROJECT_ID.appspot.com", messagingSenderId: "YOUR_MESSAGING_SENDER_ID", appId: "YOUR_APP_ID" }; const firebaseApp = initializeApp(firebaseConfig); const db = getFirestore(firebaseApp); export { db };

Then, ensure that your new firebase.js boot file is registered in the quasar.conf.js file:

javascript
boot: [ 'firebase', ],

This step ensures that Firebase will be initialized and available throughout your app.

Step 5: Install Pinia

With Firebase set up, let’s integrate Pinia for state management. To install Pinia, run the following command:

bash
npm install pinia

Once Pinia is installed, create a store for managing Firestore-related data. In the src/stores/ directory, create a new file called useFirestoreStore.js:

javascript
import { defineStore } from 'pinia'; import { db } from 'boot/firebase'; import { collection, getDocs, addDoc } from 'firebase/firestore'; export const useFirestoreStore = defineStore('firestore', { state: () => ({ items: [], loading: false, error: null, }), actions: { async fetchItems() { this.loading = true; try { const querySnapshot = await getDocs(collection(db, 'items')); this.items = querySnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); } catch (error) { this.error = error; } finally { this.loading = false; } }, async addItem(newItem) { try { await addDoc(collection(db, 'items'), newItem); this.fetchItems(); // Refresh the list after adding } catch (error) { this.error = error; } }, }, });

Here, we define a Pinia store for managing Firestore operations. The fetchItems action retrieves all documents from the items collection, and the addItem action adds a new document to the collection.

Step 6: Using the Store in a Vue Component

Now that we have set up our Pinia store, let’s use it in a Vue component. In the src/pages/ directory, create a new file called FirestorePage.vue:

vue
<template> <q-page padding> <q-card class="q-mb-md"> <q-card-section> <q-input v-model="newItem" placeholder="Enter new item" /> <q-btn label="Add Item" @click="addItem" /> </q-card-section> </q-card> <q-list> <q-item v-for="item in items" :key="item.id"> <q-item-section>{{ item.name }}</q-item-section> </q-item> </q-list> <q-spinner v-if="loading" /> <q-banner v-if="error" type="negative">{{ error.message }}</q-banner> </q-page> </template> <script> import { useFirestoreStore } from 'stores/useFirestoreStore'; import { ref } from 'vue'; export default { setup() { const firestoreStore = useFirestoreStore(); const newItem = ref(''); const addItem = () => { if (newItem.value.trim()) { firestoreStore.addItem({ name: newItem.value }); newItem.value = ''; } }; firestoreStore.fetchItems(); return { newItem, addItem, items: firestoreStore.items, loading: firestoreStore.loading, error: firestoreStore.error, }; }, }; </script>

In this component, users can add new items to the Firestore collection and display the existing items. The useFirestoreStore Pinia store handles fetching and adding data, and we display loading spinners and error messages when necessary.

Step 7: Configure Pinia in Quasar

To enable Pinia, ensure that you have configured the Pinia plugin in your Quasar project. In src/main.js, update your file to include Pinia:

javascript
import { createApp } from 'vue'; import { Quasar } from 'quasar'; import { createPinia } from 'pinia'; import App from './App.vue'; import quasarUserOptions from './quasar-user-options'; const app = createApp(App); app.use(Quasar, quasarUserOptions); app.use(createPinia()); // Initialize Pinia app.mount('#q-app');

Working with Real-time Firestore Updates

Firestore supports real-time listeners, meaning that any changes to your data are reflected immediately in your app. You can modify the fetchItems method in your Pinia store to use Firestore’s onSnapshot function instead of getDocs for real-time updates:

javascript
import { onSnapshot, collection } from 'firebase/firestore'; export const useFirestoreStore = defineStore('firestore', { state: () => ({ items: [], loading: false, error: null, }), actions: { fetchItems() { this.loading = true; const unsubscribe = onSnapshot( collection(db, 'items'), (snapshot) => { this.items = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); this.loading = false; }, (error) => { this.error = error; this.loading = false; } ); return unsubscribe; // You can call this later to stop listening }, }, });

By using onSnapshot, the UI will automatically update whenever a document in the items collection changes. This is particularly useful for real-time collaborative applications where multiple users might interact with the data simultaneously.

Conclusion

With Quasar 2, Firebase Cloud Firestore, Vue 3, and Pinia, you have a powerful stack for building modern web applications. Quasar provides a versatile framework for building cross-platform apps, Firestore ensures real-time and scalable data handling, Vue 3 offers a reactive and component-based architecture, and Pinia simplifies state management. By integrating these technologies, you can create efficient, responsive, and maintainable applications.

KCSA: Kubernetes And Cloud Native Security Associate EXAM-PREP Udemy

Post a Comment for "Quasar 2 & Firebase Cloud Firestore (with Vue 3 & Pinia)"