官术网_书友最值得收藏!

  • JavaScript by Example
  • Dani Akash S
  • 715字
  • 2021-07-02 18:39:08

Persisting data in the browser

Now, functionality-wise, our ToDo List is ready. However, on refreshing the page, the data will be gone. Let's see how to persist data in the browser. Usually, web apps connect with APIs from the server-side to load data dynamically. Here, we are not looking into server-side implementation. So, we need to look for an alternate way to store data in the browser. There are three ways to store data in the browser. They are as follows:

  • cookie: A cookie is a small information that is stored on the client-side (browser) by the server with an expiry date. It is useful for reading information from the client, such as login tokens, user preferences, and so on. Cookies are primarily used on the server-side and the amount of data that can be stored in the cookie is limited to 4093 bytes. In JavaScript, cookies can be managed using the document.cookie object.
  • localStorage: HTML5's localStorage stores information with no expiry date and the data will persist even after closing and opening the web page. It provides a storage space of 5 MB per domain.
  • sessionStoragesessionStorage is equivalent to that of localStorage, except that the data is only valid per session (the current tab that the user is working on). The data expires when the website is closed.

For our use case, localStorage is the best choice for persisting task data. localStorage stores data as key-value pairs, while the value needs to be a string. Let's look at the implementation part. Inside the constructor, instead of assigning the value to this.tasks directly, change it to the following:

constructor() {
this.tasks = JSON.parse(localStorage.getItem('TASKS'));
if(!this.tasks) {
this.tasks = [
{task: 'Go to Dentist', isComplete: false},
{task: 'Do Gardening', isComplete: true},
{task: 'Renew Library Account', isComplete: false},
];
}
...
}

We are going to save our tasks in localStorage as a string with 'TASKS' as its key. So when the user opens the website for the first time, we need to check whether any data is present in localStorage with the key 'TASKS'. If no data is present, it will return null, which means this is the first time a user is visiting the website. We need to use JSON.parse() to convert the data retrieved from localStorage from a string to an object:

  • If no data is present in localStorage (user visiting the site for the first time), we shall prepopulate some data for them using the tasks variable. The best place to add the code to persist task data in our application will be the loadTasks() function because it is called every time a change in tasks is made. In the loadTasks() function, add an additional line:
 localStorage.setItem('TASKS', JSON.stringify(this.tasks));
  • This will convert our tasks variable to string and store it in localStorage. Now, you can add tasks and refresh the page, and the data will be persisted in your browser.
  • If you want to empty localStorage for development purposes, you can use localStorage.removeItem('TASKS') to delete the key or you can use localStorage.clear() to completely remove all the data stored in localStorage.
Everything in JavaScript has an inherent Boolean value, which can be called truthy or falsy. The following values are always falsy - null, "" (empty string), false, 0 (zero), NaN (not a number), and undefined. Other values are considered truthy. Hence, they can be directly used in conditional statements like how we used if(!this.tasks) {} in our code.

Now that our application is complete, you can remove the contents of the <ul> element in the index.html file. The contents will now be directly populated from our JavaScript code. Otherwise, you will see the default HTML code flash in the page when the page is loaded or refreshed. This is because our JavaScript code executes only after all the resources are finished loading due to the following code:

window.addEventListener("load", function() {
toDo = new ToDoClass();
});

If everything works fine, then congratulations! You have successfully built your first JavaScript application and you have learned about the new ES6 features of JavaScript. Oh wait! Looks like we forgot something important!

All the storage options discussed here are unencrypted and, hence, should not be used for storing sensitive information, such as password, API keys, authentication tokens, and so on.
主站蜘蛛池模板: 西乌珠穆沁旗| 和政县| 洱源县| 松潘县| 城固县| 攀枝花市| 安岳县| 丹巴县| 军事| 上高县| 中阳县| 镇远县| 白山市| 兴山县| 高雄县| 凤城市| 连州市| 和政县| 福安市| 库车县| 满洲里市| 黔江区| 台中市| 永年县| 莱芜市| 陕西省| 元江| 罗源县| 福鼎市| 社旗县| 松滋市| 临澧县| 临朐县| 普定县| 汉源县| 汝阳县| 克东县| 浑源县| 深州市| 台中县| 梅州市|