神戸学院大学 経営学部 林坂ゼミ

React 入門トップページ

« 戻る 次へ »

React 入門

TypeScript コメント掲示板アプリの開発

ダミーデータの変更と状態確認

前のページまでの作業でローカルの環境でコメントの追加や削除ができるようになりました.ここからはバックエンドの API からコメント一覧を取得したり,投稿したりできるようにします.以前のページでコメントの初期値は API から得られるコメントと同じものを利用していました.今後 API から正しくデータを取得できているかがわかりやすくなるように,初期値のダミーデータを別の内容に変更しておきます.また,前のページで追加した WebStorage に関するコードは削除するかコメントアウトしておきます.

src/components/CommentListPage.tsximport React from 'react'
import { useState } from 'react';
// import { useState, useEffect } from 'react';
import Comment from './Comment';
import CreateForm from './CreateForm';

interface CommentData {
  id: number;
  title: string;
  body: string;
  updated_at: string;
}

interface Results {
  count: number;
  next: string | null;
  previous: string | null;
  results: CommentData[];
}

const CommentListPage: React.FC = () => {

  const [results, setResults] = useState<Results>({
    "count":10,
    "next":"http://127.0.0.1:8000/comments/?page=2",
    "previous":null,
    "results":[
      {
        "id":9999,
        "title":"ダミー",
        "body":"ダミーの本文9",
        "updated_at":"2023-11-21T11:20:00"
      },
      {
        "id":10000,
        "title":"ダミーのタイトル",
        "body":"ダミーの本文10",
        "updated_at":"2023-11-21T11:10:00"
      }
    ]
  });

  const handleDeleteButtonClick = (commentId: number) => {
    if (!window.confirm("削除しますか?")) {
      return;
    }
    const newComments = [...results.results].filter((comment) => {
      return comment.id !== commentId;
    });
    const newResults: Results = {
      "count": results.count - 1, // コメント数は1減らす
      "previous": results.previous,
      "next" : results.next,
      "results": newComments
    };
    setResults(newResults);
    // // WebStorageに保存
    // localStorage.setItem('results', JSON.stringify(newResults));
  };

  const commentItems = results.results.map((comment) => {
    return (
      <Comment
        key={comment.id}
        comment={comment}
        onDelete={handleDeleteButtonClick}
      />
    )
  });

  const handelCreateFormSubmit = (title: string, body: string) => {
    const newComments = [...results.results];  // スプレッド構文でコメントの配列だけを取り出す
    newComments.unshift({   // unshift で先頭に追加,push では最後に追加
      id: Date.now(),
      title: title,
      body: body,
      updated_at: "2024-03-18T12:00:00",
    });
    const newResults = {
      "count": results.count + 1, // コメント数は1増やす
      "previous": results.previous,
      "next" : results.next,
      "results": newComments,   // これがコメントの配列
    };
    setResults(newResults); // 画面を更新
    // // WebStorageに保存
    // localStorage.setItem('results', JSON.stringify(newResults));
  }

  // useEffect(() => {
  //   let localResults: Results;
  //   const localStorageResults = localStorage.getItem('results');

  //   if (localStorageResults === null) {
  //     localResults = results;    // 存在しない場合には初期値を設定
  //   } else {
  //     localResults = JSON.parse(localStorageResults);
  //   }
  //   setResults(localResults);
  // }, []);

  return (
    <div className="container">
      <h1>コメント一覧</h1>
      {commentItems}

      <CreateForm
        onSubmit={handelCreateFormSubmit}
      />
    </div>
  )
}

export default CommentListPage

ブラウザで動作を確認しておきます.

ts-2024-33

目次に戻る