Денис Лу
Денис Лу

Reputation: 9

Set data to localstorage

I have localstorage where i want to set my data. But i have problem. Data is not setting to localstorage it just changing. How to make data added but not changed.

    const titleProduct = '<? echo $title ?>';
    
    var session = {'products': [],'state': true};
 session.products.push({title: titleProduct});
  localStorage.setItem("cart", JSON.stringify(session));

Upvotes: 0

Views: 1219

Answers (1)

Titulum
Titulum

Reputation: 11446

You will have to follow the following procedure:

  1. Load data
  2. Change data
  3. Store data

This can be done as follows:

const rawData = localStorage.getItem("my-data") || "[]";
const data = JSON.parse(rawData);
data.push(new Date().toISOString());
localStorage.setItem("my-data", JSON.stringify(data));
console.log(data);

Here is a working example, as the code snippet component on StackOverflow does not support LocalStorage operations.

Upvotes: 1

Related Questions