Home > front end >  Making axios catch() function reusable in other components
Making axios catch() function reusable in other components

Time:06-27

I recently read this question and wanted to ask a more specific question in my scenario.

I have many different axios components in my app, which all behave a bit differently in the then() function. However, I have a universally same catch() function, and I found myself repeating this huge code block in every axios function I have. This, of course, didn't seem to follow the DRY principle very well.

Is there a way to create a more flexible Axios component I can reuse, or just a way to avoid pasting the catch() block everywhere?

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);
  });

CodePudding user response:

Simply create a catch function and reuse it wherever you want.

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);
  • Related