Last active
November 25, 2018 08:04
-
-
Save srph/df5077c07bd55a1597e551aede375719 to your computer and use it in GitHub Desktop.
axios: Open up a toast when a validation error occurs
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 instance from './instance' | |
import { toast } from '@app/components/Toast' | |
import { AxiosRequestConfig, AxiosError } from 'axios'; | |
interface IAxiosInterceptorValidationConfig extends AxiosRequestConfig { | |
appValidationError?: string | boolean | |
} | |
interface IAxiosInterceptorValidationError extends AxiosError { | |
config: IAxiosInterceptorValidationConfig | |
} | |
/** | |
* @example Disable the default validation toast | |
* axios({ appValidationError: false }) | |
* | |
* @example Provide a custom error message | |
* axios({ appValidationError: 'An error occured trying to create a contact }) | |
*/ | |
instance.interceptors.response.use(null, (err: IAxiosInterceptorValidationError) => { | |
if (err.response && err.response.status === 422) { | |
const cfg = err.config.appValidationError | |
if (cfg == null) { | |
toast('Some fields were not properly provided.') | |
} else if (typeof cfg === 'string') { | |
toast(cfg) | |
} | |
} | |
return err | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment