espresso_coffee
espresso_coffee

Reputation: 6110

How to check if value exist in Local Storage data set?

I have done some research about local storage. Seems like a pretty good option to store data. In my Single Page App I use JSON to store some of the data that is used more than once in my app. I'm wondering if I can replace JSON with Local Storage? Also what would be the benefits? So far I was able to load data in Local Storage but I couldn't check if values exist in Local Storage and how I will read the data. Here is example:

$.ajax({
        type: 'POST',
        url: 'App.cfc?method='+getMethod,
        data: {'recID':recID},
        dataType: 'json'
    }).done(function(obj){
        var numRecs = obj.RECORDCOUNT;
        jsonData[recID] = obj.DATA;
        localStorage.setItem(recID,JSON.stringify(obj.DATA));

        var firstN = jsonData[recID].hasOwnProperty('F_NAME') == true ? $.trim(jsonData[recID]['F_NAME']['value']) : '',
        lastN = jsonData[recID].hasOwnProperty('L_NAME') == true ? $.trim(jsonData[recID]['L_NAME']['value']) : '';
        console.log(localStorage[recID] +'\n'+ localStorage[recID].hasOwnProperty("L_NAME")); //Check Local Storage if value exist

    }).fail(function(jqXHR, textStatus, errorThrown){
    if(jqXHR.status == 0){
        alert("Fail to connect. Please check your internet connection.");
    }else{
        alert("Error: "+errorThrown);
    }
});

Here is example of JSON and localStorage data:

{"F_NAME":{"value":"John"},"L_NAME":{"value":"Smith"}}

Both JSON and local Storage have the same structure after I dumped the data in the console but hasOwnProperty() indicates to false in my code example above where I test loacl storage in console. I'm wondering if my code is invalid or something else is causing my code to fail. Main reason why I would like to use local storage is situation when user loose internet connection. In that case I want to save form data in local storage that way user won;t lose the data. If anyone can provide example or help with any tips please let me know. Thank you!

Upvotes: 0

Views: 2151

Answers (1)

msanford
msanford

Reputation: 12229

localStorage stores strings, which you know since you're already JSON.stringify()ing when you save. But you need to replace your check of

localStorage[recID].hasOwnProperty("L_NAME")

with

JSON.parse(localStorage[recID]).hasOwnProperty("L_NAME")

Edit: You have a whole object which you store as localStorage[recID], so you need to parse that, then access the resulting object, like:

const record = JSON.stringify({
  "F_NAME": {
    "value": "John"
  },
  "L_NAME": {
    "value": "Smith"
  }
});

console.log(JSON.parse(record)['F_NAME']['value'])

JSON.parse(record) becomes the object, then you access its descendant parameters ['F_NAME']['value']. The placement of the brackets is critical.

Upvotes: 1

Related Questions