paint-brush
How To Implement localStorage or Firebase Firestore into your JS projectby@javitocor
7,397 reads
7,397 reads

How To Implement localStorage or Firebase Firestore into your JS project

by JavitocorAugust 18th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

How To Implement localStorage or Firebase Firestore into your JS project? How To implement localStorage into your.JS project? I created a Library to store my books, with some information about them ( title, author, pages, read) and if I read it or not. I was so happy so I started to add read books and books that I planned to read, but it was empty. After some research on the web, I understood that I needed to store data somewhere or it would vanish every time I refreshed the page.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How To Implement localStorage or Firebase Firestore into your JS project
Javitocor HackerNoon profile picture

I am a great reader, I love books and I try to read as much as I can, no matter the topic, whatever, fantasy, comedy, sci-fi, educational...Books take me to another world, they make me feel, make me think, make me relax and make me disconnect from the day by day schedule. I cannot live without them. 

This is why my first approach to Javascript was to create a Library to store my books, with some information about them ( title, author, number of pages…) and if I read it or not. I know, it was a small, simple project, but what do you expect? It was my very first one, so I only wanted to practice as much as I could and make it work.

So, I created my HTML file, my `script.js` file and worked a bit on my CSS to build something nice to my eyes. After working on it for a while, I got my site looking good and my library working fine. I had a table with my books, with all the information related and a “NEW BOOK” button that brought up a form allowing me to input the details for a new book to add to the library.

All the books were an instance of the constructor Books, with a prototype to toggle the read status and all of them stored in an array. Something like this:

function Book(title, author, pages, read) {
    this.title = title;
    this.author = author;
    this.pages = pages;
    this.read = read;
}

Book.prototype.info = function () {
    return this.title + " by " + this.author + ", " + this.pages + " pages, " + this.read;
}
Book.prototype.toggleReadStatus = function () {
    this.read = this.read == 'Read' ? 'Not read' : 'Read';
}

let myLibrary = [];

Perfect! I was so happy so I started to add read books and books that I planned to read, I spent some time with it. Actually, it was my first JS creation and wanted to play around a bit. After all the work I went to have lunch and went came back to my computer and opened my page again...surprise!

No one book there, all of them gone! My array was empty, and all my previous work adding content as well. 

Bad luck or just a beginner mistake, I thought all the data will remain in my array and would keep it there forever, but it is not working that way. After some research on the web, I understood that I needed to store the data somewhere or it would vanish every time I refreshed the page.

LocalStorage

My first approach to the storage was using LocalStorage, `LocalStorage` is a type of web storage that allows JavaScript sites and apps to store and access data right in the browser with no expiration date. This means the data stored in the browser will persist even after the browser window has been closed.

Storage objects are simple key-value stores, similar to objects, but stored in `string` format. These web storage objects are not sent to the server with each request. Because of that, we can store much more. Most browsers allow at least 2 megabytes of data (or more) and have settings to configure that. 

The use of the `localStorage` is quite straight-forward, has no secrets, it provides some methods to work with it:

setItem()

With this method, you store a key/value pair into `localStorage`. It takes two parameters, the key and the value. Like this:

window.localStorage.setItem('book', 'The Lord of the Rings');
getItem()

With this method, you access to local storage by a key given. For example:

window.localStorage.getItem(‘book’); // The Lord of the Rings
removeItem()

Providing the key, this method will remove the key and its values.

window.localStorage.removeItem(‘book’);
clear()

This method, when invoked, clear the `localStorage` deleting everything.

window.localStorage.clear();
length

Returns the length of the `localStorage`.

window.localStorage.length; // returns an integer
key()

This method requires one parameter, an index, and return the key on that position in the `localStorage`;

window.localStorage.key(index);

We have already said that `localStorage` store all the data in `string` format, so how do we do to store objects? My library array, for example...

To do so we need to convert our object into a string, or into a JSON. 

We can do that:

const book = {
name:’1984’,
 author:’George Orwell’
}
window.localStorage.setItem(‘books’, JSON.stringify(book);

When we call

getItem()
method, it will return us a string with values, something like that:

window.localStorage.getItem(‘books’)
“{“book”:”1984”,”author”:”George Orwell”}”

In this case, we need to convert it into an object using the method JSON.parse().

JSON.parse(window.localStorage.getItem(‘books’));

And we will get our object back.

We neither can iterate over `localStorage`, but there is a way we can apply to do so, using the key and the length methods:

for(let i=0; i<localStorage.length; i++) {
  let key = localStorage.key(i);
  alert(`${key}: ${localStorage.getItem(key)}`);
}

So...cool! After learning all of that I implemented it in my Library project, and this time it worked as I wished. Great!!!

But there was a problem, I always want more and more, and the problem with `localStorage` is that is only accessible on the computer that it was created on. So I could not access my library from any other device or when I am not at home. LocalStorage was a solution, but not the one I was looking for.

So, back to google and spend some more time researching on the web, until I found Firebase.

Firebase Firestore

Firebase is an online database that can be set up relatively easily, allowing you to save your data to a server in the cloud. Well, actually, it is not only that, Firebase is a Backend-as-a-Service (BaaS). That means that it offers different services like authentication, analytics, hosting, cloud storage….

I paid special attention to Cloud Firestore. So I started to read the documentation and learn from an online tutorial they provide (you can find it here).

When I finished it I went back to my project and spent some time thinking about how to implement it. I already had my Library working so it was only a few changes to make.

The first step is to Sign into Firebase website using your Google account, for example. And create a Firebase project to connect to your app. No secrets to do that, just click on the ‘Add Project’ and add a Project Name,  you can also set up Google Analytics for your project, which enables you to use many of the Firebase’s products. 

After that, you need to add your app to your Firebase project. We do that by clicking the Web icon (</>). Then follow the on-screen instructions to add the app to the project. You have to provide a nickname for your app and they will give you the Firestore SDK scripts

<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>

<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>

<!-- Add Firebase products that you want to use -->  
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-database.js"></script>

And the firebase config

var firebaseConfig = {
  apiKey: "api-key",
  authDomain: "project-id.firebaseapp.com",
  databaseURL: "https://project-id.firebaseio.com",
  projectId: "project-id",
  storageBucket: "project-id.appspot.com",
  messagingSenderId: "sender-id",
  appId: "app-id",
  measurementId: "G-measurement-id",
};

Then initialize Firebase in the same script block where you added the configuration.

firebase.initializeApp(firebaseConfig);
firebase.analytics();

You should add all of that lines at the bottom of your HTML file.  

At the Firebase console, on the left, click on ‘database’ and create a database. Select a starting mode for your Cloud Firestore Security Rules (test mode is recommended for web apps, and choose the location for your database). 

When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console. And your project in Firebase is ready and connected to your app

Once we have set up all the firebase configuration the next step is add our data to our database, in my case, my library. Think that Cloud Firestore stores data in Documents, which are stored in Collections. Cloud Firestore creates collections and documents implicitly the first time you add data to the document.

You do not need to explicitly create collections or documents. Check this for more information.

In my case, I added these lines of code to my js file:

let firestore = firebase.firestore(); 
const docRef = firestore.collection('books');

Where I initialize an instance of Cloud Firestore, and then I create my collection which I called ‘books’. Everything ready to add, receive and update data in my Cloud Firestore Database. 

Firebase assigns one ID to each entry in your collection, but for readability, I decided to change it and add the title of the book instead, so when I go to my console I can see, in my collection, all the entries with the title and not a bunch of letters and numbers. To add my data I just add the input of the form, when I create a book entry, and set it to the database. Like this:

docRef.doc(`${newBook.title}`).set({
        title: newBook.title,
        author: newBook.author,
        pages: newBook.pages,
        read: newBook.read
      }).then(function(docRef) {
          console.log("Document successfully written!");
      })
      .catch(function(error) {
          console.error("Error adding document: ", error);
});

As you can see, here we use asynchronous functions to add the data to our database, setting our new book as an object. If you go to your database in the Cloud Firestore console you will see the collection ‘books’, all the books added as documents and for each document, we can find the title, author, pages and the read status. I had my library on the cloud and I could access it from my site and from the console. Cool!

Time to update my library, every time I read a book I need to update the read status from ‘Not Read’ to ‘Read’. I added these lines to my script:

 docRef.doc(`${book.title}`).update({
   read: item.read
 });

With the method update you can modify your documents by the key given, in my case I only wanted to modify the read status so I only changed that field.

How do we remove a document? As everything with Firebase, it is not complicated, I only needed to use the delete() method and add the key I wanted to delete. And...deleted! No secrets!

docRef.doc(`${book.title}`).delete();

And that was all, I got my library ready to access from everywhere and I could access my data from my app and from my Cloud Firestore Database.

Conclusion

As you can see store the data of your projects it will not be a problem from now on. You can use your browser’s `localStorage` and keep the data locally forever, and if you want to access it from everywhere you can easily implement Firebase Firestore in your project and access your data in an easy and secure way.

I usually implement Firebase in most of my projects since it's an amazing tool. You can also use it for your hosting, authentication and many other things it offers. That will come in another article very soon. 

Thank you for reading.

Happy coding!