Skip to content

Instantly share code, notes, and snippets.

@srph
Last active November 25, 2018 08:04
Show Gist options
  • Save srph/df5077c07bd55a1597e551aede375719 to your computer and use it in GitHub Desktop.
Save srph/df5077c07bd55a1597e551aede375719 to your computer and use it in GitHub Desktop.
axios: Open up a toast when a validation error occurs
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