A
A
Awake2022-03-29 19:46:21
PHP
Awake, 2022-03-29 19:46:21

How to correctly write values ​​to localStorage?

There is a page that contains a product and an "add to cart" button. When the button is clicked, the product ID (taken from the database) is written to localStorage. The problem is that I don't understand how to correctly implement key to write value to it (which corresponds to the product ID). In the JS file, I've marked the keyName as 'products'. And now, when adding a value, it is permanently assigned the products key. Those. I add, for example, a product with ID = 1. I get "products" in lS with the value "1". I add a product with ID = 2, the value "products" in lS is overwritten from "1" to "2", etc.

Here is the code from the product page:

<h1><i><?=Html::encode($product->product_name)?></i></h1>
<p><img src="https://i.blogs.es/96715c/screenshot_5596/450_1000.jpeg" alt="Sony PlayStation 5" style="width:350px; height:290px" class="leftimg"></p>

<fieldset>
    <legend><b> Описание продукта </b></legend>
    <p><?=Html::encode($product->info)?></p>
</fieldset>

<button class="k"><a class="product_link_id" data-id="<?php echo $product->ID?>">Купить</a></button>
/*
<script>
    const btn = document.querySelector('.k > a');
    btn.addEventListener('click', function () {
        btn.innerHTML = 'Уже в корзине'
    });
</script>
*/
<?=Html::encode($product->product_price)?> рублей.


And here is the JS code for adding a product to localStorage:

let count = {

};

this.keyName = 'products';

// Получаю ID'шник кнопки.
document.querySelector('.product_link_id').onclick = () => {
    getItemId(event.target.dataset.id);
};

// Убираю object Object из localStorage
localStorage.setItem(this.keyName, JSON.stringify(count));
const di = localStorage.getItem(this.keyName);
id = JSON.parse(di);

// Добавление товара в корзину
const getItemId = id => {
    count[id]++;
    console.log(localStorage.setItem(this.keyName, id));
};


As I understand it, this is due to the fact that my 'keyName' is just statistically scored as 'products'. But here's how to do it differently, I'm not really fumbling.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shamanov, 2022-03-30
@Awake_Pulse

localStorage.setItem(this.keyName, JSON.stringify(count));
const di = localStorage.getItem(this.keyName);
id = JSON.parse(di);

do you understand what your code is doing?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question