mirror of
https://github.com/Myzel394/kleckrelay-website.git
synced 2025-06-20 08:15:26 +02:00
49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import {AxiosError} from "axios"
|
|
import {useRef} from "react"
|
|
import {SnackbarKey, useSnackbar} from "notistack"
|
|
import {useTranslation} from "react-i18next"
|
|
|
|
import {ERROR_SNACKBAR_SHOW_DURATION, SUCCESS_SNACKBAR_SHOW_DURATION} from "~/constants/values"
|
|
import {parseFastAPIError} from "~/utils"
|
|
|
|
export interface UseErrorSuccessSnacksResult {
|
|
showSuccess: (message: string) => void
|
|
showError: (error: Error) => void
|
|
}
|
|
|
|
export default function useErrorSuccessSnacks(): UseErrorSuccessSnacksResult {
|
|
const {t} = useTranslation()
|
|
const {enqueueSnackbar, closeSnackbar} = useSnackbar()
|
|
const $errorSnackbarKey = useRef<SnackbarKey | null>(null)
|
|
|
|
const showSuccess = (message: string) => {
|
|
if ($errorSnackbarKey.current) {
|
|
closeSnackbar($errorSnackbarKey.current)
|
|
$errorSnackbarKey.current = null
|
|
}
|
|
|
|
enqueueSnackbar(message, {
|
|
variant: "success",
|
|
autoHideDuration: SUCCESS_SNACKBAR_SHOW_DURATION,
|
|
})
|
|
}
|
|
const showError = (error: Error) => {
|
|
const parsedError = parseFastAPIError(error as AxiosError)
|
|
|
|
if ("detail" in parsedError) {
|
|
$errorSnackbarKey.current = enqueueSnackbar(
|
|
parsedError.detail || t("general.defaultError"),
|
|
{
|
|
variant: "error",
|
|
autoHideDuration: ERROR_SNACKBAR_SHOW_DURATION,
|
|
},
|
|
)
|
|
}
|
|
}
|
|
|
|
return {
|
|
showSuccess,
|
|
showError,
|
|
}
|
|
}
|