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?

React19でuseを使うとAn unsupported type was passed to use(): async functionエラーが出る

Last updated at Posted at 2025-01-02

はじめに

React19を使い始めてエラーがでたのでまとめておきます

問題

以下のようなコードを書いたところエラーになりました。

async function fetchManageBook() {
  const response = await fetch("http://localhost:8080/books");
  const data = (await response.json()) as BookManageJson[];

  return data.map((book) => {
    return new BookManage(book.id, book.name, book.status);
  });
}

function App() {
  const books = use(fetchManageBook());

}
async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.

解決方法

Promiseを返すということはできているのですが、肝心なのはReactはクライアントコンポーネントということです。

クライアントコンポーネント内ではasync関数useEffectの中で実行しないと再レンダリングや複数コンポーネントでの実行などで何度も実行されてしまい「コンポーネントの実行は予測可能で一貫性のある結果を返す」という原則を守れなくなってしまいます。

簡単に言うとuseはレンダリングフェーズで作成されるPromiseに対応していません。

async function fetchManageBook() {
  const response = await fetch("http://localhost:8080/books");
  const data = (await response.json()) as BookManageJson[];

  return data.map((book) => {
    return new BookManage(book.id, book.name, book.status);
  });
}

const fetchManageBookPromise = fetchManageBook();

function App() {
  const books = use(fetchManageBookPromise);

}

このように1度だけPromise関数を作成して実行すれば動くようになりました。

おわりに

すこしReactの考え方が理解できた気がします。

参考

0
0
1

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?