Created
January 21, 2021 17:30
-
-
Save augustolazaro/e2461ce322093dec6a0647f32caf6947 to your computer and use it in GitHub Desktop.
Extend useMutation to support retries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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