Recientemente leí esta pregunta y quería hacer una pregunta más específica en mi escenario.
Tengo muchos componentes axios diferentes en mi aplicación, que se comportan de manera un poco diferente en la función then(). Sin embargo, tengo una función catch() universalmente igual, y me encontré repitiendo este enorme bloque de código en cada función axios que tengo. Esto, por supuesto, no parecía seguir muy bien el principio DRY.
¿Hay alguna forma de crear un componente Axios más flexible que pueda reutilizar, o simplemente una forma de evitar pegar el bloque catch() en todas partes?
axios .patch/delete/get/post( "API ROUTE URL", { withCredentials: true, } ) .then(function (response) { // stuff like... // setDrafts(response.data.results); // setState(response.data); // alert(message); }) .catch(function (error) { // this portion is the same universally if (error.response) { console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { console.log(error.request); } else { console.log('Error', error.message); } toast.error( `ERROR ${error.response.status}: See console log for more info and please report this incident`, { duration: 4000, position: 'bottom-center', } ); console.log(error.config); });Simplemente crea una catch function y reutilízala donde quieras.
const catch_func = (error) { // this portion is the same universally if (error.response) { console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { console.log(error.request); } else { console.log('Error', error.message); } toast.error( `ERROR ${error.response.status}: See console log for more info and please report this incident`, { duration: 4000, position: 'bottom-center', } ); console.log(error.config); } axios .patch/delete/get/post( "API ROUTE URL", { withCredentials: true, } ) .then(function (response) { // stuff like... // setDrafts(response.data.results); // setState(response.data); // alert(message); }) .catch(catch_func);