typescriptsession-storage

Sessionstorage.SetItem does not update


I have below code, do you have any idea why sessionstate would not update? Result before update is 3 social security numbers and I can see that it tries to update 100 new social security numbers but when I check after the update, it is still the three same security numbers as before the update.

 window.onbeforeunload = () => {
        const ssnLs = $("#members-list-table")
            .DataTable()
            .rows({ filter: "applied" })
            .data()
            .map((item: any) => {
                return item.socialSecurityNumber;
            })
            .toArray();
        
        //added this line for testing - to see what value was here before I update
        var localStorageWithMembersArray1 = JSON.parse(localStorage.getItem("socialnumbers"));
       

        sessionStorage.setItem("socialnumbers", JSON.stringify(ssnLs));
        
        //added this line for testing - to see what value is here after I update
        var localStorageWithMembersArray = JSON.parse(localStorage.getItem("socialnumbers"));

    };

Solution

  • I think you may just be using the wrong storage based on your example.

    You are setting to sessionStorage but are reading from localStorage. Setting a value in sessionStorage will not update it in localStorage, nor the other way.

    Try switching your last line to

    var localStorageWithMembersArray = JSON.parse(sessionStorage.getItem("socialnumbers"));
    

    And you should see the update.