1

I'm currently working on a project, in which I have to load an array from localStorage and from this loop through it to generate elements.

I have the saving process working as expected, however when it comes down to loading it - I recieve the following error.

TypeError: undefined is not a function (evaluating 'mainInfo.forEach')

Below you are able to see the code which is throwing this error.

var mainInfo = [];
var subInfo = [];
mainInfo = localStorage.StaffAppMainList;
subInfo = localStorage.StaffAppSubList;
finalOutput = "";
console.log(mainInfo.length);
mainInfo.forEach(function(item) {
    var theTitle = item.title;
    var url = "Pages/SubInfo.html?info=" + theTitle;
    finalOutput = finalOutput + "<li><a href='" + url + "'>" + item.title + "</a></li>";
    $("#homeList").html(finalOutput).listview().listview("refresh");
});

The line the error is thrown on is -

mainInfo.forEach(function(item) {

Currently I'm unsure of what is causing this error, and so any advice will be greatly appreciated.

2
  • Which browser and version you checking this on? Commented Jul 5, 2014 at 18:55
  • can you please make a demo fiddle where we can see the issue ? Commented Jul 5, 2014 at 18:55

2 Answers 2

4

Local storage (aka Web Storage) only stores strings. If you want to persist an array, you can JSON encode it prior to storage and decode it when retrieving.

// storing
var mainInfo = [];

localStorage.setItem("StaffAppMainList", JSON.stringify(mainInfo));

// retrieving
mainInfo = JSON.parse(localStorage.StaffAppMainList);

If you try to store anything that's not a string, an empty string will be stored, hence the error because strings don't have a forEach method.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that clears it up. Did not know that localStorage only held strings. Thank you!
1

It's because typeof mainInfo === 'string'. localStorage stores strings. You need to parse it somehow. For example if mainInfo was serialized to JSON. You need JSON.parse(mainInfo).forEach(..)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.