Siyah Klasör
Siyah Klasör

Reputation: 51

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

Upvotes: 1

Views: 634

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

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);
});

Upvotes: 2

Related Questions