Getting started with Cloud Firestore for the web – Firebase Fundamentals

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody and welcome to this firebase fundamentals video where i'm going to show you how to get up and running quickly using firestore in your web application now this video assumes that you have already gotten started with the initial firebase setup using something like webpack or roll up as david has described in his getting started video if you don't know what i'm talking about i recommend you check out his video first and then coming back to this one before continuing and if you are looking for like a more detailed explanation around some of the things i'm doing how firestore really works underneath the hood or like the difference between a document and a collection i would recommend that you check out the getting started firecast that will be a little more detailed and should be available sometime after i make this video and when it is we will link to it in the description below alright i guess that's enough preamble for now let's get coding okay so i'm gonna go ahead and start with a nearly empty project kind of like what david had at the end of his video so i have my code here in index.js which then gets compiled to my main.js file which i am reading in here now for testing purposes i'm going to go ahead and call npx webpack dash dash watch to automatically compile everything that i'm sort of changing in here and then i will serve up what's in my disk directory so that i can test it i'm going to do that by using the npm serve command here but you know you could also do this using firebase server as well either way is good so let me make a quick change to my code i'll refresh my page here and yes looks like that change got captured and served over so we are good to go okay so to get started using firestore in your project you'll first want to go to the firebase console head on over to the firestore tab and click this create database button you're going to select your initial set of security rules and your database location for me that's us west and then once that's done you will go back to your web project now if you've already installed the latest version of firebase using npm you should already have all the libraries you need so at the top of your code you'll just want to start importing from the firebase firestore library now if you're not going to be taking advantage of any of the real-time listeners offline support or some of the latency compensation that our client sdks provide then you could also use the firebase firestore lite library now this library only lets you perform simple crud operations but is significantly smaller in size for now though i'm going to stick to the full library then to access firestore just call get firestore in your code sometime after you've called initialize app you can also use initialize firestore if you need to initialize firestore with any non-default settings kind of like this but i am going to use the simpler get firestore for now now you should also note that as i'm doing this i'm going to need to import this function up above i'll be honest a few weeks ago my ide was doing all this for me and i almost never had to worry about it but shortly after i updated it it mysteriously stopped automatically importing for me uh no idea why but for now i'm gonna be adding all these imports manually and you'll probably need to make sure either that you are doing the same or that your ide is importing these individual functions for you now to write to a document you're first going to start with a document reference and to create one of these you will call the doc function pass in your reference to firestore and then the path to your document now pads in firestore always take the form of collection document collection document and so on which means document paths should always have an even number of elements first the collection then the document then the subcollection and so on so in this case i'm going to be writing to the you know 20 21 09 14 document in the daily special collection now this document here is using an absolute path but you can also use relative paths by calling doc passing in your initial document reference and then a path to a child off of that document reference like so okay to write to a document you're going to use the set dot command you'll pass in the reference to the document which we created up above as well as the document data that you want to write which i will just add up above here generally speaking you're going to represent your document as an object consisting of key value pairs kind of like this so let me just call this function really quick i'm going to run my code and i can see my document there in the firebase console now this set dot command will write the document if it doesn't exist and it will completely replace any document that already exists at this location now if that's not the behavior you want the update doc function will only overwrite the fields that you specify while keeping all your old data in place however this update.call will throw an error if the document doesn't already exist and if that's not the behavior you want you can use the set.command with merge true passed in as your third argument this will create the document if it doesn't exist and only replace the fields that you've specified if it does which call you use really depends on what behavior you want from your app now writing to a document is an asynchronous call that returns a promise so you could put this in an async await call with appropriate error checking of course or you can use a then callback just keep in mind in both situations that this call will only continue after the write has been confirmed by the server even though it will be written locally to your cache so be careful here don't block the ui or anything while you're waiting for this call to complete because if your user is offline while they're using your app it will look like your application is frozen and to be clear most of the time you won't need to wait for this right to be confirmed before you start using it because of some fancy latency compensation that our sdk already does you'll be able to access this new data right away without actually having to wait for it to be confirmed by the server okay very often you'll want to add a new document to a collection without having to specify the document id like i did above in those kind of situations you can use the add dot call this will create a new document in your collection with a randomly generated id note that when you do this you're going to be calling addock with a collection reference instead of a document reference but other than that the call looks pretty similar to setdoc i guess the other difference is that this call will return a document reference to the document that has been created in case you want to know the id or the path of the document that you just added to read in a single document use the get doc command passing in the document reference for the document that you want to read now this returns a promise which resolves to a document snapshot which is basically an object that represents your document with a snapshot you can get some metadata about the document make sure the underlying document really exists and most importantly grab the data that it contains by calling data on it so that's what i'm going to do in this example i'll see if my document exists and if it does i will extract my data like so and print out a stringified version of it to the console so just note that exists and data here are both methods not properties that's messed me up more than i care to admit and while this is nice one of the really great things about firestore is that it can also let you know in real time when your document has changed so let's look at how to do that with a snapshot listener to read a document in real time you will use the on snapshot call you'll pass in the reference of the document that you want to listen to as well as the listener itself which is a function that takes in a snapshot reference and does something interesting with the data in my case i'll once again check to see if the document exists and then print it out to the console note that this listener will fire the very first time you set up your snapshot listener as you can see here and then also fire anytime they're after when your document changes like if i were to change the price or the description of my daily special like this you can see that the listener gets called again since leaving a listener open does involve network usage for your users and database costs for you i do recommend disabling your listeners when you no longer need the data from this document now usually that's going to be during unloading type of moments in your frameworks router event or like a component's life cycle although if you are using firebase's own react fire or angular fire libraries they already handle a lot of this for you but to do this yourself the on snapshot listener automatically returns a function that you can call to unsubscribe from that listener just keep that return value in a variable somewhere and then call it at the appropriate time so being able to read in a single document is useful but often you'll want to grab multiple documents at once and you'll do this by creating a query and to create a query you will call query and then pass in a list of constraints for that query now the most common queries are ones where you're searching for a certain set of documents in a single collection so you will generally pass in a collection reference as the first constraint meaning that you're going to be querying against that particular collection now whatever else you pass in is up to you often there will be a where clause to grab for instance all orders where the drink type equals latte you could add an order by clause as well where we could sort by the order time or the customer name uh note however that this specific case of filtering on one field and then sorting by another will require my setting up a custom index which firestore will helpfully point out to me in the console through this error message i can just click on that link and i can create the index i can also limit my query to say the first 10 or the last 20 results that come in and i do recommend that you set some sort of limit to make sure you're not loading in more data than your customer would reasonably want particularly as your database grows and your collections get very large this will save them data usage and it will save you money now once you've built your query you can retrieve your documents by making a get docs call that's docs with an s and passing in your newly created query this function is very similar to the get.call described earlier except you'll be getting back a query snapshot instead of a document snapshot now a query snapshot will contain an array of documents that were returned by the query which you can get at by calling the docs method or if you want to iterate over them one at a time we let you call for each directly on the query snapshot either way you can then get at your document data by calling the data method on the individual documents that you've retrieved like so and uh whoops looks like i'm getting nothing here oh that's because these searches are case sensitive and latte should have a capital l all right that's better and by the way this is probably a good time to remind you that all this time through the magic of editing i have been adding all these functions get docs query even query constraints like limit and order by to my imports as i need them now this all plays into the nice tree shakeableness of the new firebase sdk which leaves your users with less code to download once it's been bundled up and as we add more features over time they'll stay out of your app until you decide you explicitly want to use them but if i were to forget to include one of these or my id weren't auto-including them properly i'd be getting errors like this where it's saying things like limit is not defined and that's why oh also i'm just going to remove this bit here since we no longer need it and queries support real-time updates as well basically all you need to do here is call on snapshot and pass in your query instead of a document reference and then in your listener callback you'll once again receive a query snapshot and you can process it the same way you would as if you had called get docs here i guess let me do it a little more functional programmary with the map function all right there you go and as before this returns a function that you can call to cancel this listener so save it at a variable so you can call it later one last thing to note here is that if one of these documents changes firestore the database will send that newer version of the document over to my client and then my client will combine that new document with the cached versions it already has and send my listener call back the entire list of 20 documents again and that's usually what you want it means that if i were say converting this list of documents into a group of list elements that i could display on screen i can just rebuild this group every time and not worry about any conditional logic here around like oh was this document changed or added or so on but you can always get that specific change data if you need it so those are the basics or you know the fundamentals of firestore on the web but let me leave you with a few quick notes before i go first as i mentioned earlier if i were to use the firebase firestore light library that will reduce my imported code size between like 60 to 80 percent but i won't have access to things like offline support latency compensation or those fancy real-time listeners in fact you can see here it's telling me that my on snapshot call is no longer defined which is sad so i'm going to go back second as i mentioned earlier my security rules are currently set up so that anybody out there can delete my entire database that's definitely something i should fix and a factor i should be considering now while i'm still designing my database instead of say two days before i launch and third if you're worried about messing with production data or just want to save a little money as you're developing try running against the emulators this involves installing the emulator from the firebase cli tool which you can do by typing firebase init or i think firebase init emulator starting it up by calling firebase emulator start and then pointing your code to the emulator like so and finally if you have more questions around how to structure your data how security rules work how pricing works or just about anything else i kind of recommend checking out the get to know cloud firestore series it's pretty good but you know i am a little biased there so those are the fundamentals for adding firestore to your web application hey if you like this video why not subscribe to our youtube channel you'll get to be the first on your block to know when we've added a new video and if you want to see more videos like this make sure to check out the firebase fundamentals playlist we'll be adding more videos to that as time goes on so thank you very much for watching i will see you soon and happy coding you
Info
Channel: Firebase
Views: 17,236
Rating: undefined out of 5
Keywords: purpose: Educate, pr_pr: Firebase, series: Firecasts, type: DevByte (deck cleanup 0-10min), GDS: Yes, getting started with cloud firestore, cloud firestore for the web, web, the web, cloud firestore, cloud firestore tutorial, how to use cloud firestore, what is cloud firestore, firebase tutorial, firebase fundamentals, firebase developer, firebase developers, google developers, firebase, google
Id: BjtxPj6jRM8
Channel Id: undefined
Length: 13min 52sec (832 seconds)
Published: Mon Sep 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.