Data Storage and Retrieval

JavaScriptJavaScriptBeginner
Practice Now

Introduction

In this Lab, we accompany Alex, a determined web developer at a bustling tech startup, who is now venturing into the realm of data persistence. After successfully creating a mechanism for tracking and displaying financial records in the personal finance tracker, the next challenge is to ensure that these records persist across browser sessions. The goal is to enable users to return to the app and find all their previously entered data intact, enhancing the app's usability and user satisfaction. This task introduces Alex to the concept of web storage, specifically leveraging the localStorage API to save and retrieve the application's state.

In this Lab, you'll learn how to use localStorage to store data locally in the user's browser, allowing for data persistence in web applications.

Knowledge Points:

  • localStorage usage
  • JSON serialisation and deserialisation (JSON.stringify, JSON.parse)

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript(("`JavaScript`")) -.-> javascript/NetworkingGroup(["`Networking`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") javascript/ToolsandEnvironmentGroup -.-> javascript/web_storage("`Web Storage`") javascript/NetworkingGroup -.-> javascript/json("`JSON`") subgraph Lab Skills javascript/variables -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/data_types -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/arith_ops -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/loops -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/array_methods -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/obj_manip -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/template_lit -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/web_storage -.-> lab-290730{{"`Data Storage and Retrieval`"}} javascript/json -.-> lab-290730{{"`Data Storage and Retrieval`"}} end

LocalStorage

localStorage offers a mechanism to store session data on the client side, with storage limits usually around 5MB. Unlike session storage (sessionStorage), data in localStorage does not disappear when the session ends.

Storing Data

The setItem() method allows you to store data in localStorage. This method takes two parameters: a key and a value.

For example:

localStorage.setItem("username", "Alice");

Retrieving Data

The getItem() method is used to read data from localStorage. This method takes one parameter: the key.

For example:

localStorage.setItem("username", "Alice");
let username = localStorage.getItem("username");
console.log(username); // Outputs: Alice

Saving Records to LocalStorage

In this step, you'll work with Alex to implement functionality that saves the financial records array to localStorage whenever a new record is added. This ensures that the user's data is stored locally on their device, making it available even after the browser is closed or refreshed.

At the beginning of script.js, before defining the addFinancialRecord function, add the following code to load saved records from localStorage and initialize the financialRecords array:

Modify the script.js to load records from localStorage:

document.addEventListener("DOMContentLoaded", function () {
  let records = JSON.parse(localStorage.getItem("records")) || [];
});
  • The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
✨ Check Solution and Practice

Implement Record Persistence

Add the logic to store the record in localStorage in the addRecord function:

document.addEventListener("DOMContentLoaded", function () {
  const saveRecords = () => {
    localStorage.setItem("records", JSON.stringify(records));
    renderRecords();
  };

  const addRecord = (description, amount, type) => {
    records.push({ description, amount, type });
    saveRecords();
  };
});

Now, every time a new financial record is added, it will be saved to localStorage, ensuring data persistence.

Next, we need to implement the delete function of the accounting, before writing the delete function, we need to learn a new array operation method.

✨ Check Solution and Practice

Splice Method

The splice() method can take three parameters: the start position, the number of elements to delete, and the new elements to be added.

Syntax:

array.splice(start, deleteCount, item1, item2, ...)
  • start: The index at which to start changing the array.
  • deleteCount: The number of elements to be removed. If no elements are to be removed, this should be 0.
  • item1, item2, ...: New elements to be added to the array.

Removing Elements

To remove elements from an array, set the deleteCount parameter without needing to add new elements.

let fruits = ["Apple", "Banana", "Cherry", "Date"];
fruits.splice(1, 2); // Remove 2 elements starting from index 1
console.log(fruits); // Outputs: ['Apple', 'Date']

Adding Elements

splice() can also add elements at a specific position in the array without removing any elements. Set deleteCount to 0 and specify the elements to be added.

let fruits = ["Apple", "Banana", "Cherry"];
fruits.splice(2, 0, "Date"); // Add 'Date' at index 2
console.log(fruits); // Outputs: ['Apple', 'Banana', 'Date', 'Cherry']

Replacing Elements

By setting deleteCount and adding new elements, splice() can both remove and add elements, effectively replacing them.

let fruits = ["Apple", "Banana", "Cherry"];
fruits.splice(1, 1, "Date"); // Replace 1 element at index 1 with 'Date'
console.log(fruits); // Outputs: ['Apple', 'Date', 'Cherry']

Add the Ability to Delete Records

Adding the ability to delete records.

Write the following code in the script.js file:

document.addEventListener("DOMContentLoaded", function () {
  window.deleteRecord = (index) => {
    records.splice(index, 1);
    saveRecords();
  };
});
✨ Check Solution and Practice

Summary

In this lab, you and Alex tackled the challenge of data persistence in the personal finance tracker application. By learning to use the localStorage API, you've enabled the application to save and retrieve financial records across browser sessions, significantly enhancing the user experience. This introduction to web storage opens up new possibilities for creating more complex and user-friendly web applications.

Through hands-on practice, you've seen how data can be serialized to a string format using JSON.stringify for storage and then deserialized back into JavaScript objects using JSON.parse for retrieval. This process is crucial for managing application state in client-side web development, forming a foundational skill that will aid in your future web development projects.

Other JavaScript Tutorials you may like