dansmaculotte / vue-segment

Vue.js plugin for Segment Analytics.js
MIT License
5 stars 9 forks source link

this.$segment not loaded in store for Nuxt SSR app #15

Open Olusiji opened 3 years ago

Olusiji commented 3 years ago

I'm implementing on a NUXT universal app, I noticed that using this.$segment.track() in the store does not send events to Segment. Upon investigation, I realized that the reason is that the analytics.load() method makes an asynchronous request to pull in the Segment CDN to the script tag. However, the inject('segment', analytics) method is called before the async request is completed. So the store context is injected with an unloaded version of segment, and it does not update after the async request is completed. Curiously, the components are updated, so using this.$segment.track() within the component works.

In summary, doing this.$segment.track('Some Event') in the Vuex store does not send events.

I modified the plugin to inject segment into the context after it is loaded. Unfortunately doing this means that this.$segment will be undefined on page load. ` analytics.load = function (key, options) { // Create an async script element based on your key. const script = document.createElement('script') script.type = 'text/javascript' script.async = true script.src = 'https://cdn.segment.com/analytics.js/v1/' + key + '/analytics.min.js'

// Insert our script next to the first script element.
const first = document.getElementsByTagName('script')[0]
first.parentNode.insertBefore(script, first)
analytics._loadOptions = options

// Added this to inject segment on script load
script.addEventListener('load', scriptLoaded, false)

function scriptLoaded () {
  inject('segment', analytics)
}

}`

rtouze commented 3 years ago

Hi David,

Thank you for your feedback and sorry for my late reply. It zould be convenient for sure to access .track() method from the state store.

Unfortunately, our organization does not use Segment anymore and I won't implement the feature on my side. So feel free to fork and implement it according to your needs.

I will update readme to explain that there won't be any relevant modification in the source code for now.