javascriptjquerylocal-storagesession-storagesessionstorage

How to set/get/save data in session storage?


here is example of my data that I get after ajax call response is successful obj.DATA looks like this:

{
  "A43D": {
    "FIRSTNAME": "Mike",
    "EMAIL": "mjohns@gmail.com",
    "LASTNAME": "Johns"
  },
  "4E83": {
    "FIRSTNAME": "Steve",
    "EMAIL": "scook@gmail.com",
    "LASTNAME": "Cook"
  }
}

$.ajax({
   type: 'POST',
   url: 'AjaxFunctions.cfc?method=getCustomers',
   data: formData,
   dataType: 'json'
}).done(function(obj){
   console.log(obj.DATA);
   sessionStorage.setItem("customersData", JSON.stringify(obj.DATA));      
}).fail(function(jqXHR, textStatus, errorThrown){
   alert('Error: '+errorThrown);
}); 

Then I dump sessionStorage in console.log(sessionStorage) and I see this:

{
  "customersData": "{\"A43D\":{\"FIRSTNAME\":\"Mike\",\"EMAIL\":\"mjohnes@gmail.com\",\"LASTNAME\":\"Johnes\"},\"4E83\":{\"FIRSTNAME\":\"Steve\",\"EMAIL\":\"scook@gmail.com\",\"LASTNAME\":\"Cook\"}}"
}

So I was trying next:

sessionData = sessionStorage.hasOwnProperty(customersData[recordID]) ? JSON.parse(sessionStorage.getItem(customersData[recordID])) : null;

This is in the function where I just pass record id and then try to access that record in session storage. If I try to console.log(sessionData) all I see is null. I'm wondering how I can access specific key in customersData object inside of the session storage? Also how I would insert/edit record in sessionStorage customersData object?


Solution

  • each time you try to save/load something for the localStorage/sessionStorage and you know it is a json object, always stringify/parse it depending on the case.

    here you have your code fixed to work.

    NOTE: I tried to create a snippet but it didn't work because we can not access to the sessionStorage of a sandbox.

    NOTE2: always check what data are you going to parse, if the record doesnt exist on the storage, it will return null.

    var data = {
      "A43D": {
        "FIRSTNAME": "Mike",
        "EMAIL": "mjohns@gmail.com",
        "LASTNAME": "Johns"
      },
      "4E83": {
        "FIRSTNAME": "Steve",
        "EMAIL": "scook@gmail.com",
        "LASTNAME": "Cook"
      }
    }
    
    //here we save the item in the sessionStorage.
    sessionStorage.setItem("customersData", JSON.stringify(data));
    
    
    //now we retrieve the object again, but in a string form.
    var customersDataString = sessionStorage.getItem("customersData");
    console.log(customersDataString);
    
    //to get the object we have to parse it.
    var customersData = JSON.parse(customersDataString);
    console.log(customersData);