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.
Define the properties that are available to every instance of the service. Notice they are outside of the function definition.
// define the user collection onceconstuserCollection=db.collection("users");// hold the users retrieved from the databaseconstusers=ref<any>([]);// any error from firebase callconsterror=ref<any>(null);// when we are loadingconstloading=ref<any>(false);
Let's define the composable and the initial properties that we will be returning
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.
exportdefault()=>{constgetCollectionData=async(collection:any)=>{loading.value=true;try{constquerySnapshot=awaitcollection.get();constresults=querySnapshot.docs.map((doc:any)=>{return{...doc.data(),id:doc.id};});loading.value=false;returnresults;}catch(e){error.value=e;loading.value=false;}};// helperconstloadUsers=async()=>{users.value=awaitgetCollectionData(userCollection);};// when initialized, get all the usersonMounted(async()=>{awaitloadUsers();});return{// functionsloadUsers,//propertiesusers,loading,error,};};
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
*/constgetLocalUser=(userId:string)=>{returnusers.value.find((u:any)=>u.id===userId);};
If we want to get the data from the database
/**
* get the document from firebase and not local users
*
* @param collection
* @param id
*/constgetCollectionDoc=async(collection:any,id:string)=>{loading.value=true;try{constdoc=awaitcollection.doc(id).get();loading.value=false;return{...doc.data(),id:doc.id};}catch(e){error.value=e;loading.value=false;}};
to make this function more accessible, we have added a helper function to
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.