bilpor
bilpor

Reputation: 3921

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.

Upvotes: 1

Views: 5031

Answers (2)

Nithish
Nithish

Reputation: 6039

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"))

Upvotes: 3

Ganesh
Ganesh

Reputation: 6016

Once we get the value from sessionStorage, we need convert it into JSON in order to use it as a normal object.

try to do some changes like below..

const modifiedValue =  JSON.parse(sessionStorage.getItem('state-allRequestsandResponses'));
modifiedValue.first(40);

sessionStorage.setItem('state-allRequestsandResponses',  JSON.stringify(modifiedValue));

Hope this helps.. :)

Upvotes: 0

Related Questions