Software Archive
Read-only legacy content
17061 Discussions

Cannot save and load localstorage value

Nick_F_2
New Contributor III
934 Views

I'm trying to save a variable to local storage and load it on app start.

Here is the code for saving and is the result of a flipswitch onchange event.

function setFixView() {
    if ($('#af-flipswitch-0').is(":checked"))
            {
    window.localStorage.setItem("showallfixtures", "yes");
        } else {
    window.localStorage.setItem("showallfixtures", "no");
            }
};

A breakpoint in the debug shows this is working correctly.

Here is the code for retrieving the variable:-

 $( document ).ready(function() {
          console.log("Starting App");
         var showfixtures = window.localStorage.getItem("showallfixtures");
          console.log("Shall we show the fixtures".showfixtures);
         var fixturestate = document.getElementById("af-flipswitch-0");
         if(showfixtures == 'yes') { 
              $('af-flipswitch-0').attr('checked','checked');
         }

I am getting the following error at the console.log("Shall we show the fixtures".showfixtures); line

Uncaught TypeError: Cannot read property 'getItem' of undefined VM5353 index.html:69 (anonymous function)

The idea was to use Console.log just to show the variable had been retrieved, but ultimately I need to set the flipswitch to the previous selection.

0 Kudos
2 Replies
Nick_F_2
New Contributor III
934 Views

Sorry the error appears at var showfixtures = window.localStorage.getItem("showallfixtures"); not per my original post.

0 Kudos
Michael_O_
Beginner
934 Views

Dear Nick,

Try and change window.localStorage.getItem("showallfixtures") to localStorage.getItem("showallfixtures")

Do the same to the setitem section.

0 Kudos
Reply