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

useEffect must not return anything besides a function, which is used for clean-up.

1
Posted at

はじめに

アプリ開発中に、useEffectのデータ取得でエラーが起きました。

問題

useEffectからデータ取得しているにも関わらずエラーが起こりました。

Home
import { useAuthContext } from "../context/AuthContext";

    useEffect(async () => {
        const fetchData = async () => {
            const data = await getActionsTableLib();
            if (data?.data) {
                setTodos(data?.data);
            }
        }
        fetchData();
    },[])

解決方法

エラー文に

It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

とあり、これがヒントになりました。

async処理は関数にして非同期で実行します。そのため即時関数を使用するために変更しました。

Home
    useEffect(() => {
        (
            async () => {
                const fetchData = async () => {
                    const data = await getActionsTableLib();
                    console.log(data);
                    if (data?.data) {
                        setTodos(data?.data);
                    }
                }
                fetchData();
            })()
    },[])
        }

おわりに

参考文献

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