Happylab Logo
Published on

Day15: LocalStorage

Authors

Introduction: How to use LocalStorage for data storage and management.

Project Page: https://iris1114.github.io/javascript30/15_LocalStorage/

HTML

  • Contains a title 'LOCAL TAPAS'
  • A ul list for displaying items, initially showing 'Loading Tapas...'
  • A form with an input field and submit button for adding new items
<div class="wrapper">
  <h2>LOCAL TAPAS</h2>
  <p></p>
  <ul class="plates">
    <li>Loading Tapas...</li>
  </ul>
  <form class="add-items">
    <input type="text" name="item" placeholder="Item Name" required />
    <input type="submit" value="+ Add Item" />
  </form>
</div>

JavaScript

  • Retrieves stored items from LocalStorage and parses them into a JavaScript array
  • Defines addItem function to handle form submission events, adding new items to the array and updating LocalStorage
  • Defines populateList function to render items to the ul list
const addItems = document.querySelector('.add-items')
const itemsList = document.querySelector('.plates')
const items = JSON.parse(localStorage.getItem('items')) || []

function addItem(e) {
  e.preventDefault()
  const text = this.querySelector('[name=item]').value
  const item = {
    text,
    done: false,
  }

  items.push(item)
  populateList(items, itemsList)
  localStorage.setItem('items', JSON.stringify(items))
  this.reset()
}

function populateList(plates = [], platesList) {
  platesList.innerHTML = plates
    .map((plate, i) => {
      return `
      <li>
        <input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
        <label for="item${i}">${plate.text}</label>
      </li>
    `
    })
    .join('')
}

addItems.addEventListener('submit', addItem)
populateList(items, itemsList)

Note

  • Uses localStorage.setItem and localStorage.getItem for storing and retrieving data
  • Uses JSON.stringify and JSON.parse for data serialization and deserialization
  • Form resets after submission