ReactのuseEffectにasync関数を渡すとエラーになるので

バージョン情報

  • react 16.12.0
  • typescript 3.2

本題

Reactのhooksを初使用なので、初歩ミスが多く進捗が悪いです。

さて、今回の凡ミスは、useEffectにasyncな関数を直接渡してしまって発生したエラー。
次のようにuseEffectを書いていた。

  useEffect(async () => {
    const response = await axios.get('/api/posts.json')
    console.log(response)
  }, [])

これを実行すると、次のエラーになる。

TS2345: Argument of type '() => Promise<void>' is not assignable to parameter of type 'EffectCallback'.
Type 'Promise<void>' is not assignable to type 'void | (() => void | undefined)'.
  Type 'Promise<void>' is not assignable to type '() => void | undefined'.
    Type 'Promise<void>' provides no match for the signature '(): void | undefined'.

「useEffectにPromiseを渡すんじゃねえええ!」と。
なので、useEffectに同期間数を渡して、その中で非同期関数を実行しましょうと。
修正したコードはこちら。

  useEffect(() => {
    const fetch = async () => {
      const response = await axios.get('/api/posts.json')
      console.log(response)
    }
    fetch()
  }, [])

なおりました。

タイトルとURLをコピーしました