Skip to content
This repository was archived by the owner on Feb 20, 2025. It is now read-only.
This repository was 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

Description

@Olusiji

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

}`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions