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

React 入門トップページ

« 戻る 次へ »

React 入門

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

ボタンクリックを処理して表示内容を更新する

前のページで設置した「次のページ」ボタンをクリックしたことを検知し表示内容を更新するコードを作成します.まず,ボタンに onClick 属性を追加し,実行したい関数名 handlePrevPageButton, handleCurrentPageNext{ ... } で囲って与えます.

src/components/CommentListPage.tsx(抜粋)<div className="commentsHeader">
  <div>コメント総数:{results.count}</div>
  <div>
    <button
      onClick={handlePrevPageButton}
    >
      前のページ
    </button>
    <button
      onClick={handleNextPageButton}
    >
      次のページ
    </button>
  </div>
</div>

次に,上で指定した2つの関数を定義します.定義する場所は CommentListPage() 関数内で,return 文よりも前です.これの関数の中では実際に API にリクエストして表示内容を更新します.なお,2行目や8行目のように「!」を入れなければ「型 'string | null' の引数を型 'string' のパラメーターに割り当てることはできません。」というエラーになります.

src/components/CommentListPage.tsx(抜粋)const handlePrevPageButton = () => {
  axios.get<Results>(results.previous!)
      .then((res: AxiosResponse<Results>) => setResults(res.data))
      .catch(err => console.log(err.message));
};

const handleNextPageButton = () => {
  axios.get<Results>(results.next!)
      .then((res: AxiosResponse<Results>) => setResults(res.data))
      .catch(err => console.log(err.message));
};

ページの移動ができる状態になりました.しかし,このままでは最後のページまで進んだ後に「次のページ」ボタンをクリックすると,リクエストの URL が null 値であるために処理に失敗します.同時にコンソールには「Cannot read properties of null (reading 'protocol')」と表示されます.

ts-2024-37

したがって,リクエスト送信前に URL が null であるかどうかをチェックしておくとよいでしょう.なお,2行目と11行目で URL がnull である場合に早期リターンを行っている関係で,5行目と8行目の ! は削除しても動作するはずです.

src/components/CommentListPage.tsx(抜粋)const handlePrevPageButton = () => {
  if (results.previous === null) {
    return;
  }
  axios.get<Results>(results.previous!)
      .then((res: AxiosResponse<Results>) => setResults(res.data))
      .catch(err => console.log(err.message));
};

const handleNextPageButton = () => {
  if (results.next === null) {
    return;
  }
  axios.get<Results>(results.next!)
      .then((res: AxiosResponse<Results>) => setResults(res.data))
      .catch(err => console.log(err.message));
};

ここで一旦コード全体を確認します.

src/components/CommentListPage.tsximport React from 'react'
import { useState, useEffect } from 'react';
import axios, { AxiosResponse } from 'axios';
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"
      }
    ]
  });

  useEffect(() => {
    const url = "http://127.0.0.1:8000/comments/";
    axios.get<Results>(url)
        // .then((res: AxiosResponse<Results>) => console.log(res.data))
        .then((res: AxiosResponse<Results>) => setResults(res.data))
        .catch(err => console.log(err.message));
  }, []);

  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);
  };

  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); // 画面を更新
  }

  const handlePrevPageButton = () => {
    if (results.previous === null) {
      return;
    }
    axios.get<Results>(results.previous!)
        .then((res: AxiosResponse<Results>) => setResults(res.data))
        .catch(err => console.log(err.message));
  };

  const handleNextPageButton = () => {
    if (results.next === null) {
      return;
    }
    axios.get<Results>(results.next!)
        .then((res: AxiosResponse<Results>) => setResults(res.data))
        .catch(err => console.log(err.message));
  };

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

      <div className="commentsHeader">
        <div>コメント総数:{results.count}</div>
        <div>
          <button
            onClick={handlePrevPageButton}
          >
            前のページ
          </button>
          <button
            onClick={handleNextPageButton}
          >
            次のページ
          </button>
        </div>
      </div>

      {commentItems}

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

export default CommentListPage

目次に戻る