0

I am trying to save an array into localstorage and then get it.

localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem(savedquestionslist));

The variable 'questions' is an array.

However I get this error:

ReferenceError: savedquestionslist is not defined.

I still get the error even if I do this:

localStorage.setItem("savedquestionslist", "test");
console.log(localStorage.getItem(savedquestionslist));

Does anyone know what the issue is? Thanks

Fredrik Widerberg
  • 3,068
  • 10
  • 30
  • 42
123a
  • 21
  • 3
  • Possible duplicate of [How do I store an array in localStorage?](https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) – Vikasdeep Singh Jul 18 '18 at 13:42

3 Answers3

0

savedquestionslist needs to be a string.

console.log(localStorage.getItem('savedquestionslist'));
Josh
  • 1,455
  • 19
  • 33
0

The problem is in your syntax for getItem.

It takes in a string as an argument. You are passing a variable and the error represents that the variable savedquestionslist is not defined.

Change your code to :

localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));

An example would be

var questions = ['firstQuestion', 'secondQuestion', 'thirdQuestion'];

localStorage.setItem("savedquestionslist", questions);
console.log(localStorage.getItem("savedquestionslist"));
Aayush Sharma
  • 779
  • 4
  • 20
0

The error you're getting is because you forgot the quotes in the getItem call:

console.log(localStorage.getItem("savedquestionslist"));
// ------------------------------^------------------^

Or you can use literal access:

console.log(localStorage.savedquestionslist);

But in both cases, since local storage only stores strings, I'd use JSON, since otherwise your array won't be saved / retrieved correctly:

localStorage.setItem("savedquestionslist", JSON.stringify(questions));
console.log(JSON.parse(localStorage.getItem("savedquestionslist")) || []);

(The || [] is for if you've never set the item, it provides a default of an empty array.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875