Search code examples
jquerytypescriptkendo-gridsession-storage

sessionStorage returns undefined


I have clientside application that is using sessionStorage to move data from one view to another. my code is:

$("#reportGrid").find("input:checked").each(function () {
    rows.push($(this).closest('tr'));

    var dataItem = grid.dataItem($(this).closest('tr'));
    console.log("TicketNumber => " + dataItem.ticketNumber + " " + dataItem.lineNumber);

    // store dataItem in session Storage;
    sessionStorage.setItem('selectedRecords', JSON.stringify(dataItem));
    var retrievedObject = JSON.parse(sessionStorage.getItem('selectedRecords'));

    console.log("Begin -----------");
    console.log("userSelectedRecords => " + retrievedObject[0].ticketNumber);
    console.log("End -----------");
})  

However, the line console.log("userSelectedRecords => " + retrievedObject[0].ticketNumber); returns

Uncaught TypeError: Cannot read property 'ticketNumber' of undefined

How can I display the data from previous view?


Solution

  • Reading your code you want to loop through an array of items and grab all of the ones that are checked. Currently you are looping over the checked items and storing each one into a session variable and you keep writing over it. When you read it, you only will ever have one item. If that is what you want, than you just need to reference the object, not do an array syntax.

    console.log("userSelectedRecords => " + retrievedObject.ticketNumber);
    

    BUT I do not think that is what you want to do. I think you want to have an array of elements that the user selected. To have an array, you need to build up the list and than save the whole array when the loop is finished.

    //temp holding place for the data
    var records = [];    
    $("#reportGrid").find("input:checked").each(function () {
        var dataItem = grid.dataItem($(this).closest('tr'));
        records.push(dataItem);  //push the element
    });
    //save it to localstorage
    sessionStorage.setItem('selectedRecords', JSON.stringify(records));
    
    //now your syntax would work
    var retrievedObject = JSON.parse(sessionStorage.getItem('selectedRecords'));
    if (retrievedObject.length) { //make sure we have at least one item
        console.log("userSelectedRecords => " + retrievedObject[0].ticketNumber);
    }