Search code examples
javascriptangularsession-storage

how do I update a single value of an item in session storage


I have a SessionStorage item set with the following values:

    key : state-allRequestsandResponses
    value : "{"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}"

I want to obtain the value for first for example and change the value of 30 to say 40.

I'm having real difficulty with using sessionStorage.setItem to change this value. Can anybody give an example of how to change this value.


Solution

  • You can try below method in order to store, get the data and update

    let data = {"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}
    
    //storing the data for the first time
    sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
    

    In order to update the data in sessionStorage get the object and parse it as json object since sessionStorage will store the data as strings.

    //Get the object and parse it
    data = JSON.parse(sessionStorage.getItem("state-allRequestsandResponses"))
    data.first = 40;
    
    sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
    
    //Verify whether the data updated in sessionStorage
    console.log(sessionStorage.getItem("state-allRequestsandResponses"))