Tedbear
Tedbear

Reputation: 59

How to display data from localstorage in html upon creation

Im trying to display all the records that are in local storage. Ive currently only managed to temporarily show records upon creation however they dissapear once refreshing the page.

let tunings = [];
// example {id:1592304983049, title: 'Deadpool', year: 2015}

const addTuning = (ev) => {
    ev.preventDefault(); //to stop the form submitting
    let tuning = {
        name: document.getElementById('name').value,
        note1: document.getElementById('note1').value,
        note2: document.getElementById('note2').value,
        note3: document.getElementById('note3').value,
        note4: document.getElementById('note4').value,
        note5: document.getElementById('note5').value,
        note6: document.getElementById('note6').value
    }
    tunings.push(tuning);
    document.forms[0].reset();

    // to clear the form for the next entries
    //document.querySelector('form').reset();

    //display data 
    console.warn('added', {
        tunings
    });
    let pre = document.querySelector('#msg pre');
    pre.textContent = '\n' + JSON.stringify(tunings, '\t', 2);

    //saving to localStorage
    localStorage.setItem('MyTuningList', JSON.stringify(tunings));
}

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('btn').addEventListener('click', addTuning);
});

This here displays data upon the creation of records however id like to grab every record in local storage and display it on the html page.

//display data 
console.warn('added', { tunings });
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(tunings, '\t', 2);

Upvotes: 2

Views: 475

Answers (1)

PatricNox
PatricNox

Reputation: 3918

You'll need to parse the data to get it in correct format.

This example relies on having the existence of a storage item called tunings

  const data = localStorage.getItem("tunings"); // Store the localstorage data in variable.

  // Set it to an empty array incase the storage is empty.
  if (!tunings || !tunings.length) {
    tunings = [];
  } else {
    tunings = JSON.parse(data); // Parse the data.
  }

  console.log(tunings); // Read the data for example.

Upvotes: 1

Related Questions