♾️

TanStack Query (React Query) mutate を useEffect 内で実行したら無限ループした

2023/02/24に公開

結論

useEffectの依存関係に渡すときにuseMutateの返り値そのままではなくmutateを抜き出して渡してあげる。

const postHoge = useMutate(postHogeFunc)
const postHogeMutate = postHoge.mutate

React.useEffect(() => {
  postHogeMutate()
}, [postHogeMutate])

環境

"dependencies": {
  "react": "^17.0.2",
  "react-query": "^3.39.2"
}

起きたこと

日に1回投げるみたいなエンドポイントを無限回呼び出していた。

こういうコード

const getHoge = useQuery(['hoge'], getHogeFunc)
const postHoge = useMutate(postHogeFunc, { onSuccess: 'キャッシュ更新とinvalidateQuery' })

const isPosted = getHoge.data === '今日実行したか?'

React.useEffect(() => {
  if (!isPosted) {
    postHoge.mutate()
  }
}, [isPosted, postHoge])

参考

株式会社hitocolor

Discussion