-
-
Save arekbartnik/df8fa7b57dc54a0a4f5dd6ce5f066a1d to your computer and use it in GitHub Desktop.
magical mutation for blitz
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 { useToast } from "@chakra-ui/react"; | |
import { exists } from "app/core/utils/js-utils"; | |
import { QueryFn, useMutation } from "blitz"; | |
import { MutationOptions } from "react-query"; | |
type ShowLoginOnFailFn = (s: any) => boolean; | |
type CustomOptions = { | |
errorMessage?: string; | |
showLoginOnFail?: boolean | ShowLoginOnFailFn; | |
showErrorToast?: boolean; | |
successToastMessage?: string; | |
onFail?: any; | |
onWin?: any; | |
}; | |
export const useMagicalMutation = < | |
TResult extends QueryFn, | |
TVariables = undefined, | |
TError = Error, | |
TSnapshot = unknown | |
>( | |
c: TResult, | |
options: CustomOptions & MutationOptions<TResult, TVariables, TError, TSnapshot> = { | |
throwOnError: true, | |
} | |
) => { | |
// const { openAuthDialog } = useGlobalStore(); | |
const { | |
errorMessage, | |
showLoginOnFail, | |
showErrorToast = true, | |
successToastMessage, | |
onFail, | |
onWin, | |
...restOfOptions | |
} = options; | |
const toast = useToast(); | |
const showError = (title = "An error occurred") => { | |
toast({ | |
title: title, | |
status: "error", | |
isClosable: true, | |
position: "top-right", | |
}); | |
}; | |
type Paramz = Parameters<typeof c>; | |
const fn = async (v: Paramz[0], a?: Paramz[1]) => { | |
try { | |
const data = await c(v, a); | |
if (exists(data)) { | |
onWin?.(data); | |
if (successToastMessage) { | |
toast({ | |
title: successToastMessage, | |
status: "success", | |
duration: 1000, | |
isClosable: true, | |
}); | |
} | |
return data; | |
} | |
} catch (err) { | |
const shouldShowLoginOnFail = | |
typeof showLoginOnFail === "boolean" ? showLoginOnFail : showLoginOnFail?.(err); | |
if (showErrorToast && !shouldShowLoginOnFail) { | |
showError(errorMessage || `Error: ${err?.message}`); | |
} | |
if (shouldShowLoginOnFail) { | |
// openAuthDialog(onWin); | |
} | |
onFail?.(err); | |
} | |
}; | |
return useMutation(fn, restOfOptions); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment