LoginSignup
0
1

はじめに

この記事では、React 19 で新たに追加された useActionState という hook で簡単な実装を行い、その動作を確認してみます。

開発環境

開発環境は以下の通りです。

  • Windows 11
  • VSCode
  • JavaScript
  • React 19.0.0-rc-cc1ec60d0d-20240607
  • Vite 5.2.0
  • Node.js 20.14.0
  • npm 10.8.1

また、React 19 RC のインストール方法については、以下の記事に記載しています。

useFormStatus の実装

const { pending, data, method, action } = useFormStatus();

useFormStatus では、実行ステート、アクション実行時のフォームデータ、<form> タグの method prop (getpost)、<form> タグの action prop といった各種ステータスの取得ができます。

App.jsx
import { useState } from "react";
import { useFormStatus } from "react-dom";

function FormButton() {
  const { pending } = useFormStatus();
  console.log("🚀 ~ App ~ pending:", pending);

  return (
    <button type="submit" disabled={pending}>
      Like
    </button>
  );
}

function FormWithUserFormStatus() {
  const [likeCount, setLikeCount] = useState(0);
  console.log("🚀 ~ App ~ likeCount:", likeCount);

  return (
    <form
      action={async () => {
        const response = await fetch("https://example.com/like", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ likeCount }),
        });
        const jsonResponse = await response.json();
        setLikeCount(jsonResponse.likeCount);
    >
      <strong>Like: {likeCount}</strong>
      <hr />
      <FormButton />
    </form>
  );
}

export default App;

useFormStatus<form> タグの内側で呼び出す必要があります。
以下のように<form> タグの外側で呼び出すと、正しいステータスが取得できず、null が返ってきます。

App.jsx
function App() {
  const { pending } = useFormStatus();
  console.log("🚀 ~ App ~ pending:", pending);

  return (
    <form action={action}></form>
  );
}

動作確認

Like ボタンをクリックして、action 内の処理が開始されると、isPendingtrue になります。処理が完了すると、isPendingfalse になります。

Vite-React-Google-Chrome-2024-06-13-22-15-38.gif

所感

useActionState で事足りそう。

参考

0
1
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
1