How to use SweetAlert2 inside AXIOS.interceptors.response.use()

Viewed 645

I tried incorporating SweetAlert2 on my vue project and was able to access swal() function globally on my views using Vue.use() on my main.js.

But when I tried using it inside AXIOS.interceptors.response.use() function swal() became undefined.

this is basically what my interceptor.js file looks like.

import axios from 'axios'

let instance = axios.create({
   baseURL: '/'
});

export const AXIOS = instance;

AXIOS.interceptors.response.use(

   function(response) {
      // $swal() becomes undefined
      this.$swal('Error', 'Some kind of error', 'error')
      return response;
   }, 

   function(error) {

      // TODO:

      return Promise.reject(error)
   }
)

Any idea on how to incorporate it? or maybe you guys have a better idea on how to handle response globally?

1 Answers

The context of this may not be of your Vue instance anymore when you used it in your callback function.

Try modifying your interceptor.js with the following:

import Vue from 'vue';

And instead of using this.$swal('Error', 'Some kind of error', 'error')

Use Vue.swal('Error', 'Some kind of error', 'error');

Related