Vue3 Firebase Composable Introduction w/ Ionic Framework

Aaron K Saunders - Nov 30 '20 - - Dev Community

Firebase has come a long way and IMHO the API has gotten much easier to integrate into your applications even without third-party libraries. I was looking to do a video on integrating vuefire and after poking around for a while I decided to start with the basics first and then maybe later show a vuefire integration.

The whole project is a simple list/detail application in VueJS and Ionic Framework. We display the list, you can pull to refresh and you can click a list item to route to a detail page and load the user.

For the blog post, I am going over the firebaseService we create to access the data; the Ionic components are covered in the video linked below.

Setup the basic vue and firebase imports

import { onMounted, ref } from "vue";

// FIREBASE
import firebase from "firebase/app";
import "firebase/firestore";

const db = firebase
  .initializeApp({ projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID })
  .firestore();
Enter fullscreen mode Exit fullscreen mode

Define the properties that are available to every instance of the service. Notice they are outside of the function definition.

// define the user collection once
const userCollection = db.collection("users");

// hold the users retrieved from the database
const users = ref<any>([]);

// any error from firebase call
const error = ref<any>(null);

// when we are loading
const loading = ref<any>(false);
Enter fullscreen mode Exit fullscreen mode

Let's define the composable and the initial properties that we will be returning

export default () => {

  return {
    //properties
    users,
    loading,
    error,
  };
}
Enter fullscreen mode Exit fullscreen mode

Getting All of the Users

To get all of the users from the firestore we can query the collection. This is the function to call using the collection const we created.

  const getCollectionData = async (collection: any) => {
    loading.value = true;
    try {
      const querySnapshot = await collection.get();
      const results = querySnapshot.docs.map((doc: any) => {
        return { ...doc.data(), id: doc.id };
      });
      loading.value = false;
      return results;
    } catch (e) {
      error.value = e;
      loading.value = false;
    }
  };
Enter fullscreen mode Exit fullscreen mode

Since we will be calling the function multiple times, onMounted and it is also used when refreshing the database I have created a helper function.

export default () => {
  const getCollectionData = async (collection: any) => {
    loading.value = true;
    try {
      const querySnapshot = await collection.get();
      const results = querySnapshot.docs.map((doc: any) => {
        return { ...doc.data(), id: doc.id };
      });
      loading.value = false;
      return results;
    } catch (e) {
      error.value = e;
      loading.value = false;
    }
  };

  // helper
  const loadUsers = async () => {
    users.value = await getCollectionData(userCollection);
  };

  // when initialized, get all the users
  onMounted(async () => {
    await loadUsers();
  });

  return {
    // functions
    loadUsers,
    //properties
    users,
    loading,
    error,
  };
};
Enter fullscreen mode Exit fullscreen mode

Getting A Specific User

There are two ways to get a specific user, from the local array/cache users or to call the firestore database again.

  /**
   * get the user from the local array
   * @param userId
   */
  const getLocalUser = (userId: string) => {
    return users.value.find((u: any) => u.id === userId);
  };
Enter fullscreen mode Exit fullscreen mode

If we want to get the data from the database

  /**
   * get the document from firebase and not local users
   * 
   * @param collection 
   * @param id 
   */
  const getCollectionDoc = async (collection: any, id: string) => {
    loading.value = true;
    try {
      const doc = await collection.doc(id).get();
      loading.value = false;
      return { ...doc.data(), id: doc.id };
    } catch (e) {
      error.value = e;
      loading.value = false;
    }
  };
Enter fullscreen mode Exit fullscreen mode

to make this function more accessible, we have added a helper function to

getUser : (id: string) => getCollectionDoc(userCollection,id),
Enter fullscreen mode Exit fullscreen mode

Wrap Up

This was just a quick overview of the code for the firebase composable; there is more detail and explanation in the @youtube video attached below.

If you have any questions, feel free to leave a comment here or on the video.

This is the source code for the project that I walk thru the process of developing a firebase composable to access collections and documents.

Watch Me Code in the youtube video.

Full Project Source Code

GitHub logo aaronksaunders / vue3-firebase-composable1

vue3 composition api with firebase and ionic framework. implementing list and detail page along with pull to refresh

Vue3 Firebase Composable Introduction w/ Ionic Framework

Firebase has come a long way and IMHO the API has gotten much easier to integrate into your applications even without third-party libraries.

This is the source code for the project that I walkthru the process of developing a firebase composable to access collections and documents. Watch Me Code in the youtube video.

Setting Firebase Configuration

  • This project requires an .env file in the root directory of the project containing the project id for your firebase project
VUE_APP_FIREBASE_PROJECT_ID=xxxx-yyyyy-dev

Supporting the Work On YouTube

Please checkout the video and like and subscribe to the channel. Also if you appreciate the work, please support the efforts here.

ko-fi

ko-fi

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .