Accessing gtag inside axios interceptor

I’m measuring API response time using axios interceptors.

I want to take the result and send it to google analytics.
I’m using vue-gtag for google analytics.

Putting a call to this.$gtag.event inside an axios interceptor, in main.js, produces an error 'cannot read property of $gtag on undefined’.

My main.js is along these lines (in this order)…

import axios from…
import vue-axios from …
Vue.use(Vueaxios, axios)

import vue-gtag from …
vue.use(vue-gtag, {config stuff …})

new Vue({…})

axios.interceptors.response.use(function(x) {

this.$gtag.event( … {})

return x…
}

Has anyone got suggestions on how I can access the gtag from inside an interceptor?

idk how vue-gtag is installed on the vue installed, but make sense to refer to it using

Vue.gtag

Or something like this.
This in this context should be window (you can check with a console.log(this) and see if you find gtag)

this is here not Vue.
If you want it to be your vue instance you have to set this inside your component e.g.

...
new Vue({
 created(){
    axios.interceptors.response.use((x) => { // <<-- arrow function here !!
      this.$gtag.event( … {})

      return x…
    })
 }, ....
});
...

Thanks Dan - I’ll try it out.

Hi Abern - thanks for the idea. This is originally how it was coded - but I was getting the same error.

I doubt that.
Either you didn’t use an arrow function on that part or you didn’t use it inside the component where gtag plugin was used.
This IS how it should have been coded. Because it works https://jsfiddle.net/abernh/42fL8v5d/ .

Hi Abern - thank you the fiddle! appreciate the extra effort. I don’t know what else to say other that the picture above, showing the arrow and the error.

EDIT - I see your comment refers to component - it’s not in a component.

I’ve solved this.

The issue I had was not really knowing how to access the library at the top-most level of the app.

I needed to explicitly import the function I wanted

import vue-gtag, { event } from …

and then call it as

axios.interceptors.response.use(function(x) {

event( … {})

return x…
}

thanks @danieltvaz and @abernh for your suggestion. greatly appreciated.

1 Like

Interesting conclusion. Thanks for sharing.

I am surprised (and a little bit alarmed) that the imported event method uses the same configuration parameters you set with the Vue.use call.

But as long as you are not trying to use the plugin with 2 different Google accounts in the same app I guess you should be fine. :man_shrugging:

Agree with you 100% on this - it’s strange.