This page will guide you to build your first cloud firestore app.
If you’re looking to know the basics of Cloud Firestore, visit What is Cloud Firestore?
Now, we understood the basics of Cloud Firestore.
We definitely going to dig more into building complex queries and other new features in upcoming articles.
For now, this article is focused on creating your first cloud firestore app that will help you to understand the basics very well.
Let’s create a simple traditional To-Do App using Cloud Firestore.
Cloud Firestore provides the SDKs for web and mobile app. we’ll create a web-based to-do app.
Getting Started With Your First Cloud Firestore App
1. Let’s set up firestore app
1. Go to the firebase console, Take Me To Firebase Console
2. Create project in firestore
3. Take credentials for initializing the app through code
Here we go, we’re ready with our firestore app.
Furthermore, to dig into the setup, visit, Take Me To The Offical Document Of Firebase
2. Next, let’s create a simple HTML form
First of all, need to include the firebase-app and firebase-firestore libraries provided by firebase.
Furthermore, to provide decent HTML form, I’ve used bootstrap.
So, let’s see how the HTML is, filepath is index.html
<!DOCTYPE html> <html> <head> <title>Cloud Firestore: To Do App</title> <script src="http://www.thetechieshouse.com/wp-content/uploads/2017/10/firebase-app.js"></script> <script src="http://www.thetechieshouse.com/wp-content/uploads/2017/10/firebase-firestore.js"></script> <link rel="stylesheet" type="text/css" href="https://www.thetechieshouse.com/wp-content/uploads/2017/10/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Welcome to Cloud Firestore: To Do App</h1> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" id="todoText" class="form-control" placeholder="Todo Title"> </div> </div> <div class="col-md-6"> <button id="addButton" class="btn btn-success">Add</button> </div> </div> <div id="listTodos"> </div> </div> <script type="text/javascript" src="app.js"></script> </body> </html>
3. JavaScript Code To Play Around
As you can see that, we’ve created a separated file app.js with our JavaScript code and included in HTML at the bottom of the page.
3.1 Congfiuration and Initialization of App
Let’s configure and initialize the firestore app through the code, whole JavaScript included in a single file, a path is app.js.
//Configuration var config = { apiKey: "Cloud Firestore API KEY should be here", authDomain: "Auth Domain should be here", databaseURL: "Database url should be here", projectId: "Your created project ID", }; //Firebase app initialization firebase.initializeApp(config);
3.2 Define HTML elements and attach listeners to them
Now, let’s define the HTML elements in JavaScript to play with them based on their events.
//input box var todoText = document.querySelector("#todoText"); //add button var addButton = document.querySelector("#addButton"); //list element var listTodos = document.querySelector("#listTodos");
Next, allocate the listeners to the elements. So, whenever an event called, the respected function/callback should be triggered.
//event listerner for keyup event todoText.addEventListener('keyup', handleSubmit); //Attached event listerner for click event addButton.addEventListener('click', handleSubmit);
3.3 Define database reference and do the insertion
Generally, we initialize and use the database object or reference to perform the operations.
Similary, here, we’re going to create a reference that points to firestore collection.
Now, let’s take a firestore database reference.
//Database ref const todoRef = firebase.firestore().collection("todos");
Next, let’s do the insertion part by using add method.
//Handle submit function handleSubmit(e) { if (e.keyCode !== 13 && e.type != "click") { return; } const todo = todoText.value; addButton.innerHTML = "Adding..."; if (todo === "") { return; } //Add to the database todoRef.add({ title: todo, checked: false, createdAt: (new Date()).getTime() }).then(function(docRef) { todoText.value = ""; addButton.innerHTML = "Add"; }).catch(function(error) { console.log(error); }) }
3.4 Render the real time data from database
Now, let’s render the todo list real time using OnSnapshot in-built method.
// Listener for rendering todos todoRef.orderBy("createdAt", 'desc').onSnapshot(function(docSnapShot) { listTodos.innerHTML = ""; docSnapShot.forEach(function(doc) { todo = doc.data(); todo.id = doc.id; //Container to append the child for HTML var container = document.createElement("p"); //Checkbox var checkBox = document.createElement("input"); //Set type to checkbox checkBox.setAttribute("type", "checkbox"); //Set id to the checkbox checkBox.setAttribute("data-id", todo.id); //Set checked checkBox.checked = todo.checked; //Attached a listener checkBox.addEventListener('change', handleCheckToggle); //Create Title Block var titleBlock = document.createElement("span"); //Define the innher HTML for title titleBlock.innerHTML = " " + todo.title + " "; //Add the checkbox to the DOM container.appendChild(checkBox); //Title block appended container.appendChild(titleBlock); //Append to the list on HTML listTodos.appendChild(container); }) })
3.5 Update the checkbox status data in real time database
Now, let’s update the database realtime on any event. Here, we’re updating the value of checkbox on select/unselect.
//On checkbox click update database function handleCheckToggle(e) { var targetElement = e.target; var checked = targetElement.checked; var id = targetElement.dataset.id; todoRef.doc(id).update({ checked: checked, }) }
Finally, you’re ready with your first cloud firestore app, run it in the browser. https://www.thetechieshouse.com/first-cloud-firestore-app.
You will be able to see the output as shown below.
To conclude, first cloud firestore app will help you out in,
- Set up firestore app
- Initialize your firestore app using SDK
- Do the database operations with the firestore app
- Real time rendering from the database
Here, is the full source code, First Firestore App – Example
Moreover, I hope, you love this article and excited to work on cloud firestore in your real-world projects.
Stay Tuned, I will keep you posted for further interesting articles.
Meanwhile, if you’ve any questions/suggestions, feel free to share your comments below.
Finally, don’t forget to share this article!
Happy Coding!
Leave a Reply