Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to edit a value in localStorage with TypeScript

I am working on a simple "Green Light, Red light" game using Angular, and I am storing players with their score and maxScore using localStorage.

I can already read each property from the array stored in the localStorage, but now I am stuck on modifying those values once I click a button.

This is the test array I am currently working with:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"name":"test1","score":3,"maxScore":8},{"name":"test2","score":10,"maxScore":22}]

This array is stored with a single key named "players", so it is an array of players.

My component looks like this:

game.component.ts

export class GameComponentComponent implements OnInit {
  highScoreLS: number = this.getHighScoreData();
  scoreLS: number = this.getScoreData();

  highScore: number = 0;
  score: number = 0;
  state: string = 'RUN';

  faArrowRightFromBracket = faArrowRightFromBracket;
  faShoePrints = faShoePrints;

  constructor() {}

  ngOnInit(): void {}

  addPoint() {
    this.score++;
    if (this.score > this.highScore) {
      this.highScore = this.score;
    }
    this.changeHighScore();
    this.changeScore();
  }

  removePoint() {
    this.score--;
    if (this.score < 0) {
      this.score = 0;
    }
    this.changeHighScore();
    this.changeScore();
  }

  changeState() {
    if (this.state === 'RUN') {
      this.state = 'PAUSE';
    } else {
      this.state = 'RUN';
    }
  }

  getScoreData() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    let sc = item.score;
    return sc;
  }

  getHighScoreData() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    let hs = item.maxScore;
    return hs;
  }

  changeHighScore() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    item.maxScore = this.highScore;
    localStorage.setItem('players', JSON.stringify(item));
  }

  changeScore() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    item.score = this.score;
    localStorage.setItem('players', JSON.stringify(item));
  }
}

And the html looks like this:

game.component.html

<div class="navbar navbar-dark bg-dark">
  <div class="container">
    <h2>Hi! đź‘‹</h2>
    <a class="navbar-brand" routerLink=""
      ><fa-icon [icon]="faArrowRightFromBracket"></fa-icon
    ></a>
  </div>
</div>

<div class="container flex vh-100">
  <div class="row m-3">
    <h3>HIGH SCORE: {{ highScoreLS }}</h3>
  </div>
  <div class="row m-3">
    <div class="card p-3">
      <h3>{{ state }}</h3>
    </div>
  </div>
  <div class="row m-3">
    <h3>SCORE: {{ scoreLS }}</h3>
  </div>
  <div class="row m-3">
    <div class="col">
      <button class="btn btn-outline-success" (click)="addPoint()">
        <fa-icon [icon]="faShoePrints"></fa-icon>
        Left
      </button>
      <button class="btn btn-outline-success" (click)="removePoint()">
        Right
        <fa-icon [icon]="faShoePrints"></fa-icon>
      </button>
    </div>
  </div>
</div>

The problem is, when I click the button to add or remove a point, it deletes the whole array of players, and creates a new one like the following:

{"name":"test1","score":0,"maxScore":1}

I have been working for a couple of days with localStorage so I do not know exactly what I am missing or what I am doing wrong.
My idea is to edit those values, score and maxScore, but I can’t figure it out how.

EDIT
The first time I click on add a point, it edits only the maxScore, but once. The next time I click, it gives me this error:

ERROR TypeError: localStorageItem.find is not a function
    at GameComponentComponent.changeScore (game-component.component.ts:83:33)
    at GameComponentComponent.addPoint (game-component.component.ts:34:10)

>Solution :

You’re calling localStorage.setItem with just the single item and not the whole array so every subsequent "finds" you’re trying will fail.

Try this instead:

localStorage.setItem('players', JSON.stringify(localStorageItem));

Though I have to say, there’s loads of duplicate code in just that one component. You should read some articles on data structures and state management.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading