2
2

More than 3 years have passed since last update.

Effect callbacks are synchronous to prevent race conditions.

Posted at

useEffectで非同期処理を実行したかった時に怒られたのでメモ。

起こったこと

こういうふうにasync関数をuseEffectの第一引数に設定したところ

const getAllBlogs = async () => {
    if (user) {
        blogService.setToken(user.token)
        const blogs = await blogService.getAll()
        setBlogs(blogs)
    }
}
useEffect(getAllBlogs, [user])

以下のようなエラーが出てしまいました。
スクリーンショット 2021-03-20 22.09.08.png

Put the async function inside らしいです。丁寧にサンプルコードまで提示してくれています。

修正

useEffectの第一引数の関数内に新しくfetchBlogsというasync関数を定義し、その中でawait getAllBlogs()としました。


const getAllBlogs = async () => {
    if (user) {
        blogService.setToken(user.token)
        const blogs = await blogService.getAll()
        setBlogs(blogs)
    }
}
useEffect(() => {
    const fetchBlogs = async () => {
        await getAllBlogs()
    }
    fetchBlogs()
}, [user])

が、まだエラーが出ています。
スクリーンショット 2021-03-20 19.59.54.png

fetchBlogsの中に全部入れるとエラーは出なくなりました。


useEffect(() => {
    const fetchBlogs = async () => {
        if (user) {
            blogService.setToken(user.token)
            const blogs = await blogService.getAll()
            setBlogs(blogs)
        }
    }
    fetchBlogs()
}, [user])

2
2
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
2
2