npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

treacker

v1.0.2

Published

A tracking library for React

Downloads

56

Readme

Treacker

The Tracking library for React.


Installation

  1. Install it by running npm i --save treacker or yarn add treacker
  2. Use it with vanilla JS or React

Example

You can find an example in this codesandbox.

Why another tracking library?

Check my post on the practical dev.

Docs

🍦For Vanilla

import { trackingManager } from 'treacker'

const INITIAL_PARAMS = {
  appVersion: 1
}

const onTrackingEvent = (event) => {
  sendEvent(event)
}
const tracking = trackingManager({ id: 'conversation', onTrackingEvent, initialParams: INITIAL_PARAMS })

Parameters:

  • id integer|string: Identifies the instance if you have several, if there not, it fallbacks to the default one.
  • onTrackingEvent function: This will be the function invoke with the payload described in this section.
  • initialParams object: Add the initial params to the instance
  • ready bool: (defaults to false), if set to true it will start dispatching tracking events instantly

Interface

ready

It's used to let the instance know when the data is ready, and the events tracked by that moment will be flushed.

  • params object (optional): will append the data passed as the unique argument to the initialParams when creating the instance.
// from the example above
const extraParams = {
  userId: 123
}
tracking.ready(extraParams)

Internally it will have the following parameters:

{
  appVersion: 1,
  userId: 123
}

track

The main function, it is used to track the events. It accepts two arguements with the following signature:

  • eventName string
  • params object

The params are going to be appended the internal memoized parameters of the instance.

tracking.track('user.login')

// will invoke the registered callbacks with the following payload:
{
  eventName: 'user.login',
  timestamp: 1572257317504,
  params: {
    appVersion: 1,
    userId: 123
  }
}

With extra parameters on the event:

// role equals to 'admin' somewhere in the app
tracking.track('user.login', { role })

// will invoke the registered callbacks with the following payload:
{
  eventName: 'user.login',
  timestamp: 1572257317504,
  params: {
    appVersion: 1,
    userId: 123,
    role: 'admin'
  }
}

registerListener

Add more listeners to the events after creating the event.

const newCallbackFunction = event => {
  sendToOtherTrackingService(event)
}
tracking.registerListener(newCallbackFunction)

getParams

In case you need to get the current params in order to do some computations (which is not recommended, but just in case). You can access to the instance data parameters.

console.log(tracking.getParams())

// will return
{
  appVersion: 1,
  userId: 123,
}

⚛️ For React

The library uses internally React's Context architecture.

1. Create a provider with TrackingProvider

The provider expects you to let it know when you're are ready by set the ready prop to true.

In the following example, we initialise the TrackingProvider and we wait for the getUser promise to result in order to let the component know that it's ready to flush the events triggered.

import { useState, useEffect } from 'react'
import { TrackingProvider } from 'treacker'

import UserComponent from './user-component'
import Room from './room'

const INITIAL_PARAMS = {
  locale: 'en',
  app_version: 1
}

const handleOnTrackingEvent = event => {
  // do stuff when the event has been fired.
}

const Layout = ({ getUser, getRoom, rooms }) => {

  const [ready, setReady] = useState(false)
  const [params, setParams] = useState(INITIAL_PARAMS)
  useEffect(() => {
    getUser().then((user) => {
      setParams(state => ({
        ...state,
        userId: user.id,
      })
      setReady(true)
    })

    getRoom()
  }, [])
  return (
    <TrackingProvider params={params} onTrackingEvent={handleOnTrackingEvent} isReady={ready}>
      <UserComponent {...user} />
      {
        rooms.map(room => <Room {...room} />)
      }
    </TrackingProvider>
  )
}
  1. Connect the children component using useTracking, it will connect to the closest TrackingProvider, with the same interface exposed when creating an instance.
import { useEffect } from 'react'
import { useTracking } from 'treacker'

const UserComponent = () => {
  const tracking = useTracking()
  useEffect(() => {
    tracking.track('user-component.loaded')
  }, [])

  return (
    // ... the component implementation
  )
}

In the case of the rooms, if we want to track when the room has been loaded and pass the roomId:

import { useEffect } from 'react'
import { useTracking } from 'treacker'

const Room = ({ roomId }) => {
  const tracking = useTracking()
  useEffect(() => {
    tracking.track('room.loaded', { roomId })
  }, [])

  return (
    // ... the component implementation
  )
}

Using the library with class components

For the cases that you need to use the library with class components, import the context and use it as a common provider/consumer component:

import { TrackingContext } from 'treacker'

class MyClass extends React.Component {
  componentDidMount() {
    const tracking = this.context;
    
    tracking.track('user-component.loaded')
  }
}
MyClass.contextType = TrackingContext;

HOC

WIP: withTracking()

Using tracking as a prop:

import { useEffect } from 'react'
import { withTracking } from 'treacker'

const Component = ({ tracking }) => {
  useEffect(() => {
    tracking.track('my-event')
  }, [])
}

export default withTracking()(Component)

Using useTracking and a custom provider:

import { useEffect } from 'react'
import { withTracking, useTracking } from 'treacker'

const Component = () => {
  const tracking = useTracking()

  useEffect(() => {
    tracking.track('my-event')
  }, [])
}

export default withTracking({ id: 'custom-provider' })(Component)

Using useTracking and a custom provider and a custom event listener:

import { useEffect } from 'react'
import { withTracking, useTracking } from 'treacker'

const customEventListener = event => {
  // do special stuff
}

const Component = () => {
  const tracking = useTracking()

  useEffect(() => {
    tracking.track('my-event')
  }, [])
}

export default withTracking({ id: 'custom-provider', onTrackingEvent: customEventListener })(Component)

Registering event callbacks

There are two ways to register a listener:

  1. From an instance: After creating the instance, a registerListener method is exposed, from you need to pass the callback function reference as an argument, like you would to using addEventListener.
const newCallbackFunction = event => {
  sendToOtherTrackingService(event)
}
tracking.registerListener(newCallbackFunction)
  1. Globally Another option is, in case you don't have access to the instance to registering using the global function exposed: registerTrackingListener. The signature is the following:
  • eventListener function (required): callback function reference.
  • id: is is the id of the already created instance, in case you don't provide one it will fallback to the global one.
import { registerTrackingListener } from 'treacker'

const newCallbackFunction = event => {
  sendToOtherTrackingService(event)
}

In case you want to register it to the global (default):

registerTrackingListener({ eventListener: newCallbackFunction })

Or you have a custom instance somewhere in your app:

registerTrackingListener({ id: 'my-custom-id', eventListener: newCallbackFunction })