LoginSignup
0
0

More than 3 years have passed since last update.

Effect callbacks are synchronous to prevent race conditions. Put the async function inside: エラーが発生した時の対処法

Posted at

useEffect内で非同期処理を記入しようとしたら、ESlint拡張機能に怒られた

エラー時のコード

example.jsx
  useEffect(async() => {
    await getTrashPageList();
  }, []);
ESlint拡張機能によるエラー内容
Effect callbacks are synchronous to prevent race conditions. Put the async function inside:

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

Effect callbacks are synchronous to prevent race conditions. Put the async function inside:

つまり、エフェクトコールバックは競合状態を防ぐために同期されているので、非同期関数はuseEffectの内部に書いてねーと言っている。

エラーの解消方法

example.jsx
  useEffect(() => {
    async function fetchData() { // featchDataという関数を定義し、それにasyncをつける
      await getTrashPageList();
    }
    fetchData(); // ここで呼び出す
  }, [trashPageData]);
  1. 関数を新たに定義し、その関数にasyncをつけてあげる
  2. その関数をuseEffect内部定義する
  3. その定義した関数を同ブロック内で呼び出す

これで解決!

参考サイト

How to call an async function inside a UseEffect() in React?

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