Skip to content

Instantly share code, notes, and snippets.

@augustolazaro
Created January 21, 2021 17:30
Show Gist options
  • Save augustolazaro/e2461ce322093dec6a0647f32caf6947 to your computer and use it in GitHub Desktop.
Save augustolazaro/e2461ce322093dec6a0647f32caf6947 to your computer and use it in GitHub Desktop.
Extend useMutation to support retries
import {
useMutation,
MutationHookOptions,
MutationFunctionOptions,
} from 'react-apollo'
import { DocumentNode, ExecutionResult } from 'graphql'
interface MutationOptions extends MutationHookOptions {
retry: {
max: number
}
}
export const useMutationWithRetry = (
mutation: DocumentNode,
options: MutationOptions
): any => {
const {
retry: { max },
...fnOptions
} = options
const [_fnMutation, result] = useMutation(mutation, {
...fnOptions,
})
const fnMutation = (
newOptions: MutationFunctionOptions,
attemps = 0
): Promise<ExecutionResult<any>> => {
return _fnMutation(newOptions).catch((error) => {
if (attemps + 1 >= max) {
throw error
}
return fnMutation(newOptions, attemps + 1)
})
}
return [fnMutation, { ...result }]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment