Skip to content
This repository has been archived by the owner on Feb 20, 2025. It is now read-only.

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

Open
Olusiji opened this issue May 2, 2021 · 1 comment
Open

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

Olusiji opened this issue May 2, 2021 · 1 comment

Comments

@Olusiji
Copy link

Olusiji commented May 2, 2021

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
Copy link
Contributor

rtouze commented May 25, 2021 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants