0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript:8.状態を保存(localStorage)

Posted at

やりたいこと

ページをリロードしても選択中の食べ物の状態やスコアがそのまま保持されている。

こういう時はlocalStrageを使う

保存先   :  ブラウザ
保存期間  :  永続(リロードや再起動しても残る)
扱える型  :  文字列(JSON.stringify()で保存、JSON.parse()で復元)
ブラウザ上に文字列を保存して、リロードする際に保存した文字列を利用して元の状態に復元するという事を実施する!!

実装ステップ

①保存する:選択されているfoodのインデックスを保存する

ts
private saveState(): void {
    const selectedIndexes = this.foodItems
        .map((item, index) => selected ? index : null)
        .filter((i): i is number => i !==null);

    localStorage.setItem('selectedFoods',JSON.stringify(selectedIndees));
}

1.this.foodItemsの中で選択されているものはインデックスを返す。
 違う場合はNULLを返す
2.数字だけを返す
  ⇒ 選択されているインデックス番号だけの配列を作る

②復元する:初期化時にlocalStorageを読み取り復元

ts
private loadState(): void {
    const stored = localStorage.getItem('selectedFoods');
    if(!stored)return;

    const indexes = JSON.parse(stored) as number[];

    indexes.forEach(indes => {
        const item = this.foodItem[index];
        item.selected = true;
        item.element.classList.add('food--active');
    });

    this.TdScore = this.foodItems
        .filter(item => item.selected)
        .reduce((sum, item) => sum + item.score, 0);

    this.score.update(this.TdScore);
    this.updateSelectedList();
    this.updateScoreMessage?.();
}

1.localStorageに保存した「selectedFoods」の文字列を「stored」に代入
2.storedを配列に戻し「indexes」に代入
3.インデックスを同じfoodItemをセレクト状態にする
4.スコアを集計
5.各メソッドを実行して元の状態に復元する

③各処理の最後に保存を追加

ts
this.saveState(); //reset(),handleClick().removeButtonなどの最後に追加

localStorageを常に最新状態にするため各メソッドにsaveStateを配置する。

④初期化時にloadStateを呼び出す

ts
constructor(){
    this.setupFoods();
    this.loadState();
}

setupFood()を読んで、fooditemsのリストが完成してから復元する。
「foodItemを作る⇒保存されてた選択を復元する」この順番が大切。

大まかな流れ

1.localStorageにインデックスを保存
2.初期化時にlocalStorageからインデックスを読み取る
3.読み取ったインデックスを利用してページを復元

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?