Javascript - How to store player names and score using localStorage and then displays the stored data in real time

360 Views Asked by At

I am struggling with the window.localStorage. I don't know how to use it to achieve my goal. My current code just stores the player's score in the server so if I restart the server, their score will reset. I am only running it in localhost so sometimes I will need to restart my computer. I did some research and I found that the web storage seems like a good option but again I don't know to do it.

Here's what I want to achieve:

  1. I would like to store a player's name and their score respectively in web local storage using the window.localStorage.
  2. I want to display the stored data in real time so the displayed data will keep changing as the stored data changes.

So next time after restarting the server and starting the game again, the players won't lose their score record and they can continue playing with their existing score.

I would appreciate it if anyone could make maybe a sample code and then I will incorporate them into my code.

I will also show a part of my current .js code that gives a point on every winning and also displays the winning streak inside the addContent, in case it could help and maybe you could create the code based on that, that would be really great, here is my existing code:

let wins = {};

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'];
    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>`
        );
}}

From the code above, userName is the player's name, wins[userName] is the payer's score streak, and insde the addContent is where it displays the winning streak/count.

1

There are 1 best solutions below

2
Adeel Ahmed On

You can define a key name while storing data to local storage which should be a string and value should be a string

localStorage.setItem('key', 'value');

and to print, you can use getItem

console.log(localStorage.getItem('key'));