Search code examples
javascripthtmllocal-storageweb-storage

How to add point to an existing score value that works after refreshing the bowser


I have an issue with adding a point to the existing/old score value after I refresh the web page. Instead of adding a point to the existing/old score, it replaces it, which means if there's an existing/old score already, it will reset and start from 1 again. I don't want that. I want it continues.

Here's my current code, the localStorage code is on the bottom:

function addPhoto(data, mode) {
    // DATA
    let userName = data.uniqueId;
    let userAvatar = data.profilePictureUrl;
    let word = ['Nice going','That’s better than ever','That’s first class work','I’m impressed','Nothing can stop you now','Well done','Good job','You did it','That’s the way','You rock','I knew you could do it','Keep up the good work','That’s clever','Way to go','Outstanding','Tremendous','Fantastic','You are amazing','No one can beat you','You are the chosen one'];
    let words = word[Math.floor(Math.random()*word.length)];

    if (mode == "winner") {
    wins[userName] = wins[userName] || 0
    wins[userName]++
        addContent(
                `<div style="text-align:center;font-size: .8rem;">
                    <div style='padding-bottom:.25rem;color:#1881FF;'>👏🏻👏🏻 `+ words + `</div>
                    <div style='padding-bottom:.5rem;font-weight: bold;color:#20B601;'>`+ userName + ` ❗</div>
                    <div>
                        <img src="`+ userAvatar + `" style="width:135px;height:135px;border-radius: 30%;border: 1px solid #20B601;box-shadow: 0 0 7px 1px #20B601;"/>
                        <span style='color:#EA0C0C; font-weight: bold;'>&nbsp;&nbsp;&nbsp;&nbsp;Wins: x`+ wins[userName] + `</span>
                    </div>
            </div>`
        );
}

    // Set
    $("#lastWinner").html(`<div class="lastWinPopUp winnerpopup">
                            <p>Winner:</p>
                            </br>`+ userName + `
                            </br></br><img src="`+ userAvatar + `" style="width:80px;height:80px;border-radius: 10%;box-shadow: 0 0 7px 1px #000000;"/>
                            </br></br>Win streak:<p id="score"></p>
                          </div>`
                          ); 
                          //<span style='color:#EA0C0C; font-weight: bold;'>&nbsp;&nbsp;&nbsp;&nbsp;Wins: x`+ wins[userName] + `</span>

    // Sound
    playSound(3);

    const username = userName;
    const score = wins[userName];
    localStorage.setItem(username, score)

    var existing = localStorage.getItem(username);

    var data = existing ? existing + score : score;

    localStorage.setItem(username, data);
    document.getElementById("score").innerHTML = localStorage.getItem(username);
}

The result from this current code is:

After refreshing the page, it will replace the existing/old score, and start again from 1 point. As you can see I tried adding the var existing an attempt to add a point to the existing/old score.

But instead of adding 1 point, it adds number 1 literally next to the current value which will become 11(becomes 1 because it still replaces the existing/old score), and becomes 22, 33, and so on as it adds more points.

Could anyone modify the code for me?


Solution

  • as mentioned, the values within the store will be strings so cast the value to a number and then use ++ to add

    let username='teddybear';
    
    var existing = localStorage.getItem(username);
    if( !isNaN( existing ) ){
        var data = parseInt( existing );
    }else{
        var data=0;
    }
    data++;
    localStorage.setItem( username, data ); 
    

    The problem with the original code is that you explicitly set the localStorage back to a default value on each page load/reload.

    This piece:

    const username = userName;
    const score = wins[userName];
    localStorage.setItem(username, score)
    

    Instead of doing that, check whether the value held is null or NaN and proceed from there. This is a slightly modified version of the above with some example data

    // hard-coded.... for demo only
    let wins={
        'teddybear':2,
        'fungus':0,
        'homer':3,
        'orinnocco':7
    };
    let username='teddybear';// hard-coded.... for demo only
    
    
    var existing = localStorage.getItem( username );
    if( existing!=null && !isNaN( existing ) ){
        var data = parseInt( existing );
    }else{
        var data=wins[ username ];
    }
    data++;
    localStorage.setItem( username, data );