Rajesh Saravanan
Rajesh's blog

Follow

Rajesh's blog

Follow
React LocalStorage - JavaScript Exercise #21

React LocalStorage - JavaScript Exercise #21

Build a simple React application that uses LocalStorage

Rajesh Saravanan's photo
Rajesh Saravanan
ยทMar 18, 2023ยท

4 min read

Overview

In this exercise, you will create a simple React application that uses LocalStorage to store and retrieve data. LocalStorage is a browser-based storage mechanism that allows data to be stored and accessed even after the browser is closed.

Instructions

  1. Create a simple form that allows the user to enter a key-value pair.

  2. When the form is submitted, store the key-value pair in LocalStorage.

  3. Create a table that displays all of the key-value pairs stored in LocalStorage.

  4. Add functionality to the table that allows the user to delete specific key-value pairs.

  5. Add a button that clears all of the key-value pairs stored in LocalStorage.

Bonus requirements

  1. Add validation to the form to ensure that the user enters both a key and a value.

  2. Add error handling for cases where LocalStorage is not available (e.g., in incognito mode).

  3. Implement sorting functionality for the table based on the key or value.

  4. Use LocalStorage events to update the table in real time when data is added, deleted, or modified.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React LocalStorage exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the LocalStorage exercise

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem('data'));
    if (storedData) {
      setData(storedData);
    }
  }, []);

  const handleFormSubmit = (event) => {
    event.preventDefault();
    const key = event.target.elements.key.value;
    const value = event.target.elements.value.value;
    if (key && value) {
      const newData = [...data, { key, value }];
      setData(newData);
      localStorage.setItem('data', JSON.stringify(newData));
      event.target.reset();
    }
  };

  const handleDelete = (key) => {
    const newData = data.filter((item) => item.key !== key);
    setData(newData);
    localStorage.setItem('data', JSON.stringify(newData));
  };

  const handleClearAll = () => {
    setData([]);
    localStorage.removeItem('data');
  };

  return (
    <div>
      <h1>React LocalStorage Exercise</h1>
      <form onSubmit={handleFormSubmit}>
        <label htmlFor="key">Key:</label>
        <input type="text" name="key" id="key" />
        <label htmlFor="value">Value:</label>
        <input type="text" name="value" id="value" />
        <button type="submit">Save</button>
      </form>
      <table>
        <thead>
          <tr>
            <th>Key</th>
            <th>Value</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {data.map((item) => (
            <tr key={item.key}>
              <td>{item.key}</td>
              <td>{item.value}</td>
              <td>
                <button onClick={() => handleDelete(item.key)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      {data.length > 0 && <button onClick={handleClearAll}>Clear All</button>}
    </div>
  );
}

export default App;

Uses of LocalStorage:

  • Storing user preferences such as theme, language, or font size settings

  • Caching data that is frequently accessed by the user, such as recently viewed items or search history

  • Storing user-generated data that can be accessed across multiple sessions, such as a shopping cart or saved drafts

  • Storing authentication tokens or session data to persist a user's login status across multiple sessions

Data that should not be stored in LocalStorage:

  • Sensitive user information, such as passwords, credit card numbers, or social security numbers

  • Confidential company data, such as financial records or trade secrets

  • Data that needs to be updated frequently and is not critical to persist across sessions, such as real-time stock prices or weather forecasts

  • Large amounts of data that could slow down the application or exceed LocalStorage's capacity. In these cases, it may be better to use a database or cloud storage solution.

LocalStorage is a useful tool for storing and accessing data in a web browser, and can be particularly helpful in creating a seamless user experience. However, it's important to use LocalStorage appropriately and avoid storing sensitive or confidential information. With careful planning and consideration, LocalStorage can be an effective way to improve the functionality and usability of web applications.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย 
Share this