cerebral-google-analytics

Google analytics module and provider for Cerebral JS

Usage no npm install needed!

<script type="module">
  import cerebralGoogleAnalytics from 'https://cdn.skypack.dev/cerebral-google-analytics';
</script>

README

cerebral-google-analytics

Warning: This library is currently in it's infancy. It is working for a pre-production application but has not been battle tested. Use at your own risk! PR's and help are absolutely welcomed! :)

Description

Google analytics module and provider for Cerebral JS This module exposes Google Analytics as a provider, Heavily inspired by and code utilized from React-GA. Has the ability to auto-fire events based on signal change.

Install

NPM

npm install cerebral-google-analytics

Instantiate

import { Module, Controller } from 'cerebral'
import GAModule from 'cerebral-google-analytics'

const analytics = GAModule({
  // (optional) Enable debug mode
  debug: true,
  // (optional) Change to title case
  titleCase: false,
  // (optional) Additional GA options
  gaOptions: {
    // (optional) Location in state to user ID
    userId: 'myModule.path.to.userId'
  },
  // Events to fire
  events: {
    someValueChanged: {
      // (requied) State path to fire event from. Use % for simple fuzzy matching.
      // If the state in the specified path changes, a GA event will be sent.
      // This is useful when you have lots of sub-modules where the parent handles signals.
      statePath: 'myModule.%.%.form.myField.value',
      // (optional, defaults to 'stateChange') Action to send to GA
      // Ref: https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#eventAction
      action: 'Some action',
      // (optional, defaults to key (someValueChanged)) Category to pass to GA
      category: 'Some category',
      // (optional, defaults to the value that was changed) Label to pass to GA
      // Ref: https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#eventLabel
      label: 'Some label',
      // (optional) Number
      // Ref: https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#eventValue
      value: 123,
    },
  }
})

const app = Module({
  modules: { analytics }
})

const controller = Controller(app)

error

StorageProviderError

import { GoogleAnalyticsProviderError } from 'cerebral-google-analytics'

// Error structure
{
  name: 'GoogleAnalyticsProviderError',
  message: 'Some ga error'
  stack: '...'  
}

pageview

Send a page view to GA

action

function someAction({ analytics }) {
  analytics.pageview('some URL') // Could pull from state / router provider
}

modalview

event

Send an event GA

action

function someAction({ analytics }) {
  analytics.event({
    action: 'Play',
    category: 'Video',
  })
}

set

send

timing

exception

Credits

Google analytic functionality borrowed from the great React-GA library. Module/Provider functionality inspired by @cerebral's modules.