💡

HTMLからDBデータを取得して描画するまでをクラス設計を用いて実装してみた

に公開

ToDoアプリを作る中で、「サーバーのDBにあるデータをHTMLに反映したい」という場面に遭遇しました。
反映するデータが1つだけならシンプルですが、HTML上に同じ要素をデータの数だけ表示させたくて、さらにその要素にイベントを追加したかったので、単なるループ処理だと限界がありました。
そこで要素のクラスを設計することで実装しました。
今回はタスクのカテゴリ一覧をDBから取得し、クラスを用いてHTML要素として描画するという処理を過程をまとめていきます。

前回の記事

https://zenn.dev/tar0/articles/4c7f0c42275419#todoアプリ開発ログ

完成図

実装するクラス

HTMLに描画したいHTML構造をクラスで作っていきます。

HTML構造

描画するそのHTML構造を以下に示します。

<div class="categoryBoxs"><!--この要素ブロックの中にカテゴリ一覧が入る-->

    <div class="categoryBox"><!--カテゴリ1つ分の要素ブロック-->
        <div class="category"><!-- ここにカテゴリを入れる--></div>
        <div class="edit_category">
            <imb src="fig/edit.png" alt="編集ボタン"><!--登録したカテゴリーを編集するためのボタン-->
        </div>
    </div>

</div>

ツリー構造

categoryBoxs
├── categoryBox
│   ├── category
│   └── editcategory
│       └── img
└── categoryBox
     :
     :

クラスの設計

HTML構造よりクラス構造は以下のように作ることができる

class CategoryBox {
  constructor(
    private categoryName: string,
    private parent: HTMLDivElement,
  ) {}

  //method
  create() {
    const categoryBox = document.createElement("div");
    categoryBox.className = "categoryBox";
    
    const category = document.createElement("div");
    category.className = "category";
    category.textContent = this.categoryName;
    categoryBox.appendChild(category);

    this.edit_category = document.createElement("div");
    this.edit_category.className = "edit_category";
    this.edit_category.setAttribute("type", "button");
    
    const editImg = document.createElement("img");
    editImg.src = "fig/edit.png";
    editImg.alt = "編集ボタン";

    this.edit_category.appendChild(editImg);
    categoryBox.appendChild(this.edit_category);
    this.parent.appendChild(categoryBox);
  }
}

createElementで要素ブロックを作成し、appendChildで親要素にぶら下げていきます。

HTMLに表示

DBからデータの取得

fetch関数を使ってHTTPリクエストをサーバーに送りデータを受け取ります

const categoryDateInServer = async () => {
  try {
    const res = await fetch('http://localhost:3000/get-category', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });

    const data: { id: number, category: string }[] = await res.json();
    console.log('サーバーからの応答', data);
  } catch (err) {
    console.error('通信エラー', err);
  }
}

*サーバー側の処理は省略

インスタンスの作成とHTMLに表示

DBから受け取ったdataからHTML要素ブロックのインスタンスを作る。
先ほどのコードに追加

const categoryDataInServer = async () => {
  try {
    const res = await fetch('http://localhost:3000/get-category', {
      method: 'GET',
      headers: { 'Content-Type': 'application/json' }
    });

    const data: { id: number, category: string }[] = await res.json();
    console.log('サーバーからの応答', data);
    data.forEach(element => {
      const categoryBox = new CategoryBox(element.category, categoryBoxs);
      categoryBox.create();
    });
  } catch (err) {
    console.error('通信エラー', err);
  }
}

categoryDataInserver();

new Category()で要素ブロックのインスタンスを生成し、.create()で生成したインスタンスをHTMLに表示させる
forEach()データベースから取得した行の数だけインスタンスが作られるため、結果一覧が表示できる。

Discussion