Search code examples
javascriptjsonvariablesrefresh

Why is my localstorage not keeping the variable's value after refresh?


So I have some code that I want to keep a certain variable's value after I go on to another page and when I come back to the original page and press a certain button it increases it value and it keeps the increades value. The problem is that the code doesn't seem to work as intended. The default value of the variable is 0, on button press it is increased with 2 and saved using the localstorage and I'm sent to my other page and then when I go back to the original page and press the same button again the variable is again 2. Why is that? Here's my code:

$(document).ready(function()
{
    var isShoes = false
    var isShirt = false
    var oneMoreShoe = false
    var buttonClicked = 0;

    $('#purchaseShoes').on('click', function()
    {
        buttonClicked+=2;
        var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
        var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
        var retainClicksCount = localStorage.getItem('buttonClicked')
        var actualClickCount = JSON.parse(retainClicksCount)
        isShoes = localStorage.setItem('isShoes', true)
        alert(retainClicksCount)
        if(retainClicksCount>= 4){
            oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
         }
    })
    
})

Solution

  • $(document).ready(function()
    {
        var isShoes = false
        var isShirt = false
        var oneMoreShoe = false
        var buttonClicked = 0;
        
        if (localStorage.getItem('buttonClicked')) // check if button click exists in storage and assign it to your variable
        {
            buttonClicked = localStorage.getItem('buttonClicked');
        }
        $('#purchaseShoes').on('click', function()
        {
            buttonClicked+=2;
            var Shoes = localStorage.setItem('img_shoes', '/static/Images/Sneakers.png')
            var clicksCounter = localStorage.setItem('buttonClicked', JSON.stringify(buttonClicked))
            var retainClicksCount = localStorage.getItem('buttonClicked')
            var actualClickCount = JSON.parse(retainClicksCount)
            isShoes = localStorage.setItem('isShoes', true)
            alert(retainClicksCount)
            if(retainClicksCount>= 4){
                oneMoreShoe = localStorage.setItem('oneMoreShoe', true)
             }
        })
    })
    

    Each time you update your page your buttonClicked variable becomes = 0. You need to check if local variable exists,if it's so you get value for your script variable from localstorage and then you add 2 and work with it.