27
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】useEffectを非同期にしてfetchしたデータをuseStateのset関数で更新する

Posted at

個人の備忘録です。

React HooksのuseEffectを使っていて、useEffect内で外部からfetchしてきたデータをuseStateのset関数で更新しようとした時のメモ。

環境

  • React.js v17.0.2

結論

  • useEffect に直接 async はつけれない
    • Promiseを返してしまうから
  • useEffect内で非同期関数を作る

// ❎
useEffect(async () => {
  const res = await fetchData();
  setValue(res);
}, []);

// 🟢
useEffect(() => {
  // 非同期関数の作成
  const fetchFunction = async () => {
    const res = await fetchData();
    // set関数で値の更新
    setValue(res);
  };
  // 非同期関数の実行
  fetchFunction();
}, []);
27
46
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
27
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?