javascriptangularionic-frameworklocal-storageangular-local-storage

How to fetch localstorage data in different screen?


I am using Ionic and I am saving the preference of a user in localstorage.

Now, I would want to show this data in the profile of this person (so in a different screen / page), yet I have no clue how I should fetch this data.

Could someone help me out?

// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
  document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
  var id = e.target.id,
      item = e.target,
      index = favorites.indexOf(id);
  // return if target doesn't have an id (shouldn't happen)
  if (!id) return;
  // item is not favorite
  if (index == -1) {
    favorites.push(id);
    item.className = 'fav';
  // item is already favorite
  } else {
    favorites.splice(index, 1);
    item.className = '';
  }
  // store array in local storage
  localStorage.setItem('favorites', JSON.stringify(favorites));
});

// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage

This is my Codepen: https://codepen.io/CrocoDillon/pen/pIlKB


Solution

  • As long as you are staying on the same domain, you should have access to the same localStorage object. So this should work:

    var favorites = JSON.parse(localStorage.getItem('favorites')) || [];