Recipe 2.3

Persisting Simple Objects

Fill out the user profile with a first and last name, then click Save. The profile data will be stored as an object in local storage. When you refresh the page, the previously saved profile data is shown.

Demo

User Profile

Code

JavaScript
/**
 * Given a user profile object, serialize it to JSON and store it in local storage.
 * @param userProfile the profile object to save
 */
function saveProfile(userProfile) {
  localStorage.setItem('userProfile', JSON.stringify(userProfile));
}

/**
 * Loads the user profile from local storage, and deserializes the JSON back to
 * an object. If there is no stored profile, an empty object is returned.
 * @returns the stored user profile, or an empty object
 */
function loadProfile() {
  return JSON.parse(localStorage.getItem('userProfile')) || {};
}

const form = document.querySelector('form');

const profile = loadProfile();
console.log('Loaded profile data:', profile);
form.elements.firstName.value = profile.firstName || '';
form.elements.lastName.value = profile.lastName || '';

form.addEventListener('submit', event => {
  event.preventDefault();
  profile.firstName = form.elements.firstName.value;
  profile.lastName = form.elements.lastName.value;
  console.log('Persisting profile:', profile);
  saveProfile(profile);
});
HTML
<form>
  <div class="card">
    <div class="container-fluid card-body">
      <h2 class="card-title">User Profile</h2>
      <div class="row">
        <div class="mb-3 col">
          <label for="firstName" class="form-label">First Name</label>
          <input autofocus type="text" name="firstName" id="firstName" class="form-control">
        </div>
        <div class="mb-3 col">
          <label for="lastName" class="form-label">Last Name</label>
          <input type="text" name=="lastName" id="lastName" class="form-control">
        </div>
      </div>
      <div class="row">
        <div class="col">
          <button class="btn btn-primary">Save</button>
        </div>
      </div>
    </div>
  </div>
</form>
Web API Cookbook
Joe Attardi