React LocalStorage – JavaScript Exercise #21

Overview

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

Instructions for React LocalStorage

  1. Create a simple form that allows the user to enter a key-value pair.
  2. When the user submits the form, 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. LocalStorage events 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 React 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
  • We cache data that the user frequently accesses, such as recently viewed items or search history.
  • The application stores user-generated data that users can access 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
  • Regularly update data that 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!

Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top