简体   繁体   中英

localstorage deletes the previous data, how can I add new data?

Where am I making a mistake? When I add a new data, it deletes the previous data and adds a new one. However, I want it to be like this; If there is an id, do not add it, otherwise new data will be added with the previous data.

let array_item = [];

$('#bookmark').click(function() {

    let id = $(this).data("id");
    // We place the data from data-id into the array item array.

    array_item.push(id);

    let parsed = JSON.stringify(array_item);
    localStorage.setItem('array_item', parsed);
    console.log(parsed);
})

Thank you in advance for your support

You need to retrieve the data in storage, add to it, and then save the result. If you don't need array_item outside the handler, that would look like this:

$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
    array_item.push(id);
    localStorage.setItem("array_item", JSON.stringify(array_item));
});

If you do need it outside the handler, but the handler is the only place you add to it, that looks like this:

const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    array_item.push(id);
    localStorage.setItem("array_item", JSON.stringify(array_item));
});

Or you could have a function that does it that you can call from multiple places:

const array_item = JSON.parse(localStorage.getItem("array_item") || "[]");
function addArrayItem(item) {
    array_item.push(item);
    localStorage.setItem("array_item", JSON.stringify(array_item));
}
$('#bookmark').click(function(){
    let id = $(this).data("id");
    // We place the data from data-id into the array item array.
    addArrayitem(id);
});

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