Task-Manager-App and Firebase
Hey! In this article I will introduce you all to how we can integrate Realtime Database from Firebase with our javascript app and also will explain all the features that I incorporated in my app. We will go function by function.
CLICK HERE to view my app.
If anybody wants to learn how to store data in firebase, I will help you out. I will explain the whole CRUD — Create, read, update and delete. So lets begin.
Topics to be covered :-
- Creating new project in firebase
- Add firebase to our JS web app
- Create a Realtime Database
- JavaScript for CRUD — Create, Read, Update and Delete
- Explanation of my JS code for Task Manager app function by function.
Lets first start with FIREBASE — Create new project
- If (you don’t have an account){create one} else {login}.
- Go to https://console.firebase.google.com/
- Click on Add project
- Give your project a name and click continue.
- Enable or disable Google Analytics for the project based on your choice. I personally disabled.
- Click on Create Project. After the project is build you will get a message — “Your new project is ready”. Click on continue button.
- Now your project is ready.
Now lets add firebase to our JavaScript app
- Click on the icon shown in the image above to add firebase to your web app.
- Now register your app by providing a nickname. If you want to setup firebase hosting then click on the checkbox else leave it. I used netlify to host my app so I left the checkbox unchecked.
- Now click Register app button.
- Now you will get some scripts — FIREBASE SDK
<! — The core Firebase JS SDK is always required and must be listed first →
<script src=”https://www.gstatic.com/firebasejs/8.2.3/firebase-app.js"></script><! — TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries →<script>
// Your web app’s Firebase configuration
var firebaseConfig = {
apiKey: “AIzaSyAbUP_P_9MdFKxbmct**mPH6BHKZ861WVA”,
authDomain: “sampleproject-d****.firebaseapp.com”,
projectId: “sampleproject-d****”,
storageBucket: “sampleproject-d****.appspot.com”,
messagingSenderId: “15507**22530”,
appId: “1:155***322530:web:36188bcf8f***f569b2dfb”
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
5. Add the script with variable firebaseConfig to the .js file created by you in the very starting of the file.
6. Add the script with src to your html file inside head tag. I added 2 more scripts <script src=”https://www.gstatic.com/firebasejs/8.2.3/firebase-auth.js"></script>
<script src=”https://www.gstatic.com/firebasejs/8.2.3/firebase-database.js"></script>
7. Change it to the latest version mentioned in the SDK provided to you by firebase.
8. Now you are all set to create your database and perform all the CRUD operations. Click on continue to console to get started.
Now lets create our database
- Click on Realtime Database in the sidebar and then click on Create Database.
- Click on next → Keep the Start in locked mode selected→ Click on Enable.
- For now you can neither read nor write to the database.
- Go to rules tab.
- read and write would be set to false. Change it to true for both read and write and then click on Publish.
- Now your database setup is complete. You are good to run some javascript and tinker with your database now.
JavaScript for CRUD — create, read, update, delete
- Create —
firebase.database().ref(‘parentNodeName/’+ ‘childNodeName ’).set({
key1 : value1,
key2 : value2,
});
The ref function takes the path under which you need to store the data(key-value-pair).
2. Read —
firebase.database().ref(‘parentNodeName’ + ‘childNodeName’).on(‘value’, function(snapshot){
data = snapshot.val(); //The data variable will contain whole data present inside childNode
});
The ref function takes the path under which you need to read the complete data.
3. Update —
firebase.database().ref(‘parentNodeName/’+ ‘childNodeName’).update({
oldkey : newvalue,
oldkey : newvalue
})
The ref function takes the path under which you need the update the data.
4. Delete —
firebase.database().ref(‘parentNodeName’).remove();
The ref function takes the path under which you want to delete the whole data.
FIREBASE Done✔️.
Now lets look at the code of my project — Task Manager App
You can checkout the code for the project in my github repository — click here
I won’t be explaining the HTML and CSS part because I hope that my readers are well aware of it and can understand it very well. My focus will be on explaining the features and the related function in JavaScript. So lets get started.
1. Changing color of label and input field based on focus of input field
I added eventlisteners — focusin and focusout. When user clicks or focuses on the input field the color changes from gray to blue and when the user clicks somewhere else or the input field looses focus the color shift back to normal.
2. storeTask() function
The storeTask() function is invoked when the form is submitted. The data from the form is read and stored in JS variables and the fields are cleared. Then the data read is stored in the database. Each task stored in the database is represented by a unique number(code variable). I have used my own way of making the app. You can do it your own way following your own logic. After storing the data in DB, the task is displayed on the right side of the screen in form of small rectangular cards. The view changes based on screen-width. You can read about the function .insertAdjacentElement() from net. The HTML that I have mentioned here in JavaScript will be added adjacent to the element with task-header id and will remain there till you reload the window.
Note :- I have set the id of each task-item same as there unique number in the DB (stored in code variable) so when in future we need to select a particular task item and do stuff with it, it will be easy.
3. editData() function
Here when the user clicks on the EDIT TASK button, the data from that particular item card to which the button belongs is filled in the form and the buttons are changed from Add to Update Task and Cancel. The code displayed above does all these things. The UPDATE TASK button here calls the updateData() function where it passes the unique code for the task.
The code for each item is the basis for identifying unique task items displayed on the page and also update data in the DB.
4. updateData() function
This function is invoked by the UPDATE TASK button which appears when we want to update a previously stored task. When the button is pressed, the new data entered by the user is read into variables and then the data is updated to the same space in DB where the task previously belonged with the help of code. After that, the field data is cleared, the buttons are removed, the ADD button is added back and also the task is updated in the task list visible on the screen.
5. cancelUpdation() function
This function is invoked by the Cancel button which appears when we want to update a previously stored task. When we press Cancel button the data is cleared from the fields, both the UPDATE TASK and CANCEL buttons are removed and the ADD button is added to the form.
6. deleteData() function
When the button is clicked, the particular task is deleted from the DB and its card is also removed from the side bar. The totalItems key in the DB is also updated to the new value.
7. showAll() function
To know where the value of data variable comes from, refer to the full code on my github. 1st if-else — If there is no data present in the DB and also there is no info previously displayed, then info = “No pending tasks is displayed”. 2nd if-else — If there is no data present in the database and some info is previously displayed, then first remove the previous info and then display new info. If the data is present, remove all the task-items if displayed on the screen. Now run the for loop across data, store the pieces of data in different variables. The data variable contains a simple dictionary. Display the data again in form of cards for all tasks and show under My Tasks.
Talking about the small tick symbol on the extreme right — top, this represents if the task is completed or pending. User can change the status of the task by clicking on this symbol. If its color is gray then the task is pending. When you click on this, the symbol turns green, “completed” written in small is displayed under the task desc and the Edit Task button is disabled. This is my favorite feature in this app. It is cute. The status is also updated in the DB.
8. deleteAll() function
If there are 0 items stored and also no info is displayed then “No pending tasks” is displayed beneath the My tasks heading. If there are tasks present in the DB, then a confirmation is asked from the user if the user really wants to delete all the tasks or not. If the user opts for “Ok” then the data in the DB is erased and also the tasks are removed displayed beneath the My tasks heading. Also the totalItems and maxCode is updated to zero value.
Now, after deleting the tasks “All items deleted” message is shown.
9. changeStatus() function
This function deals with the tick symbol. It changes the status of a task and accordingly makes the necessary changes req.. At first it reads the status of the particular task from the DB for whom the tick symbol was clicked. If the status is “pending” then
- it is updated to “completed” in the DB
- the tick symbol is colored green
- the EDIT TASK button is disabled and color is changed
- also a small text “completed” is shown beneath the task desc
If status read from DB == “completed” then all the changes are set to default.
Now, all the JS functions are completed. I hope you were able to follow my words.
This app is for now open to all. There is no login signup page. I’ll soon add on that and make this a complete useful webapp.
Blogs are really a good way of debugging, sharing and also a manual for your future self so that if you forget your own code in future, it can help you trace back. I myself found 2 bugs in my code while writing this blog and solved the same. Also found that there is a repetition of code which for now I am not changing. Writing blogs is a really good thing.
Dear Readers
If you find any bug or malfunctioning or any problem with the app, please feel free to reach me. I would be glad.
email — gagansinghkalsi4126@gmail.com
Instagram username — gagan_singhkalsi11
Thanks
The whole code is pushed to my repository to which link is here. Hope you enjoyed. This was my first project using firebase.
Cheers🍻