Retrieving data objects from localstorage and reload them into array

Viewed 63

I have taken some key points from this site already when it comes to transferring data to and from local storage. However, it does not seem to work properly. In short, I am trying to load data in the form of an array containing objects, to and from the local storage. I am aware that it is saved as a string within local storage and have then used JSON formatting to solve that problem, it is also where I think the problem might be when there is objects within objects. However, in its current state, it does not seem to work. Any ideas?

var students = [{name: "Petrina", age: "20"}];
  function saveList(){
    localStorage.setItem('somekey', JSON.stringify(students));
    console.log("Saved to Local");
  }
  function loadList(){
    students = JSON.parse(localStorage.getItem('somekey'));
  }

The code gives no errors, I am using the functions in relation to loading the window.

window.onload = () => { loadList() }
3 Answers

You've added that you are calling from onload, and,
in your code you are loading into students.

add to the beginning of your code:
var students;.

Note: Some Objects need special handling.
For example: Date:

var date = new Date();
localStorage.date = JSON.stringify(date);
date = new Date(JSON.parse(localStorage.date));

Answer before additional information:

key is a method of localStorage.
Don't use it.
Use students instead, for example.
Storage.key()
(This is assuming that you call the functions)

var students = [{name: "Petrina", age: "20"}];
function saveToLocalStorage(key, value){
  localStorage.setItem(key, JSON.stringify(value));
  console.log("Saved to LocalStorage");
}
function loadFromLocalStorage(key){
  console.log("Loaded from LocalStorage");
  return JSON.parse(localStorage.getItem(key));
}
console.log("students: "+students);
saveToLocalStorage("stu", students);
var st2=loadFromLocalStorage("stu");
console.log("st2: "+st2);
  • cannot be run in a snippet: sandboxed, no access to localStorage - cross origin.

It got solved! - I am unsure what the problem was. I cleared all the calls for all functions and debugged the save and load function 1 at a time whilst watching the local storage data. The problem to begin with was that it simply did not save the data that got updated during runtime, hence it just kept loading values that always were the same. @iAmOren's idea by creating a function that returns a value might have done it, however I am unsure why. Thanks for the responses & Support!

Related