简体   繁体   中英

How to retrieve objects from sessionStorage?

I'm generating list of dishes(which are objects) and when user clicks button the InitializeFoodList() should add selected item to sessionStorage. Then in RetrieveDataFromCart() I want to loop over the sessionStorage and show all this items in console.

The problem is the end result is that the item property is null or it's just showing the last added item and next one are null.

Anyone knows a better way to achieve this?

 var list = [{ id: 1, name: "Spaghetti", price: 15, category: "main", pictureSrc: "images/food/spaghetti.jpg" }, { id: 2, name: "Lasagne", price: 20, category: "main", pictureSrc: "images/food/Lasagne.jpg" }, { id: 3, name: "Coca-cola", price: 5, category: "drinks", pictureSrc: "images/food/cola.jpg" }, { id: 4, name: "Chicken", price: 12, category: "main", pictureSrc: "images/food/chicken.jpg" }, ]; function InitializeFoodList() { var foodList = $('#foodList'); for (let i = 0; i < list.length; i++) { const element = list[i]; var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>'; foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>"); $('#add' + i).click(function() { sessionStorage.setItem("cart", JSON.stringify(element)); }); } } function RetrieveDataFromCart() { var elements = []; for (let i = 0; i < sessionStorage.length; i++) { var element = JSON.parse(sessionStorage.getItem(localStorage.key(i))); elements.push(element); console.log(element.name); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <button onclick="InitializeFoodList()">Click me</button> <button onclick="RetrieveDataFromCart()">Retrieve</button> <ul id="foodList" class="list-inline"></ul> </div> 

I would just keep whole array in storage under one key

Then you can add/remove or modify objects in array in memory and store modified array every time you change it

function getStoredCart(){
    // return stored array and if not existing return an empty array
    return JSON.parse(sessionStorage.getItem('cart') || '[]')
}

function saveCart(array){
   sessionStorage.setItem("cart", JSON.stringify(array)); 
}

// example deleting item
function deleteItem(item){
    var itemIndex = cartList.indexOf(item)
    cartArray.splice(itemIndex,1); // remove from stored array       
    saveCart(cartArray ); // save it back into storage
}

// example adding item
function addItem(itemObject){       
    cartArray .push(itemObject); // push new object to array       
    saveCart(cartArray ); // save it back into storage
}


// keep array reference in variable whole time page is active
var cartArray = getStoredCart();

$.each(cartArray , function(i, item){
    // add the html for each item and use `item` reference in click handlers when doing modifications
})

You are using sessionStorage correctly but there are some issues in this snippet . Firstly, while setting item in sessionStorage, you are adding 'cart' as key everytime so it results in overriding the previous value stored as items in sessionStorage are stored as key value pairs and keys should be unique otherwise it updates the previous value stored at the same key.

So I have added value of i with key name 'cart' ie 'cart' + i . You can use any of unique keys according to your use case . And Secondly instead of getting particular key using localStorage Use session storage (seems to be some typo)

Updated snippet

var list = [{
    id: 1,
    name: "Spaghetti",
    price: 15,
    category: "main",
    pictureSrc: "images/food/spaghetti.jpg"
},
{
    id: 2,
    name: "Lasagne",
    price: 20,
    category: "main",
    pictureSrc: "images/food/Lasagne.jpg"
},
{
    id: 3,
    name: "Coca-cola",
    price: 5,
    category: "drinks",
    pictureSrc: "images/food/cola.jpg"
},
{
    id: 4,
    name: "Chicken",
    price: 12,
    category: "main",
    pictureSrc: "images/food/chicken.jpg"
},
];

function InitializeFoodList() {

var foodList = $('#foodList');

for (let i = 0; i < list.length; i++) {
    const element = list[i];
    var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>';
    foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>");
    $('#add' + i).click(function() {
    sessionStorage.setItem("cart" + i, JSON.stringify(element));
    });
}
}

function RetrieveDataFromCart() {

var elements = [];

for (let i = 0; i < sessionStorage.length; i++) {
    var element = JSON.parse(sessionStorage.getItem(sessionStorage.key(i)));
    elements.push(element);
    console.log(element.name);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM