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?

ReactとNext.jsで作るメモ帳アプリ:inputやtextareaのデータをフォームなしでデータベースに送信する

Posted at

はじめに

こんにちは。Reactの学習のために簡易なメモアプリを作ることにしたのですが、せっかくなので趣味の競馬で使えるような競馬特化メモアプリを作成することにしました。
競馬とは勝負の世界。馬券購入締め切りの直前まで1分たりとも無駄にすることはできません。そんな中いちいち登録ボタンを押さないとメモを登録できないような実装では、時間をロスし当てられるレースも外してしまいます。「あと1分あれば当てれてた」なんて言い訳とはおさらばしましょう。

debounceでリクエストを調整する

今回の実装では、inputタグやtextareaタグの値をuseStateで管理し、メモが更新されるたびにデータベースに送信します。しかし、一文字一文字変更があるたびにリクエストを送信すると、リクエストが過多になってしまいます。そこで、lodashのdebounce機能を使い、入力から一定時間が経過した後にリクエストを送信する方法を採用しました。

debounceとは?

debounceとは、特定の関数が頻繁に呼び出されるのを防ぐための技術であり、最後のイベントが発生してから一定時間が経過した後にのみ関数が実行されます。

debounceの使い方

まず、lodashをインストールします

npm install lodash

次に、Reactコンポーネント内でdebounceを呼び出します

page.js
import { debounce } from 'lodash';

実装

textareaタグの設定

page.js
<textarea name="comment" value={comment} onChange={(e) => handleChange(e, item.id)} className={styles.commentBox}></textarea>

onChangeで呼び出す関数

page.js
const handleChange = debounce(async (e, id) => {
      const { name, value } = e.target;
      try {
          const response = await fetch('/api/update-data', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              },
              body: JSON.stringify({ id, fieldName: name, fieldValue: value }),
          });
          const result = await response.json();
      } catch (error) {
          console.error('Error updating data:', error);
      }
  },500);

実際に動かしてみると
debounce.gif

一文字ごとにリクエストが送信されていないことがわかる
スクリーンショット 2025-02-03 16.54.03.png

無事フォームなしでinputやtextareaのデータをデータベースに送信することができました!

0
0
0

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?