Retry with useMutation (React Query)

Viewed 1324

How can I do a retry when the mutation fails in react-query? If there is an error, I would like to retry the mutation 3 times.

I read this thread where Tanner mentioned that you’ll have to build your own promise retry wrapper. but, how can I do that?

My function is:

const [accessSelectPage, accessSelectPageInfo] = useMutation(
    () =>
      axios.post(
        POST_ACCESS_SELECT_PAGE_EP(token ?? ''),
        {},
        {
          headers: { 'X-Campaign-ID': campaignID }
        }
      ),
    {
      onSuccess: (responseOnSuccess) => {
        console.log('accessSelectPage', responseOnSuccess)
      },
      onError: (error) => {
        console.log('accessSelectPage error', error)
      }
    }
  )

Note: Yes, I know that v3 has an option "retry", but I'm using v2, and updating react-query is not viable for several reasons.

1 Answers

ReactQuery.v3 supports retries

  const [accessSelectPage, accessSelectPageInfo] = useMutation(
    () =>
      axios.post(
        POST_ACCESS_SELECT_PAGE_EP(token ?? ''),
        {},
        {
          headers: { 'X-Campaign-ID': campaignID }
        }
      ),
    {
      onSuccess: (responseOnSuccess) => {
        console.log('accessSelectPage', responseOnSuccess)
      },
      onError: (error) => {
        console.log('accessSelectPage error', error)
      }
    },
    {
      retry: 3
    }
  )

For ReactQuery.v2 suggest using axios-retry as it seems like v2 doesn't support retry according to source code

Related