segmentio / analytics-next

Segment Analytics.js 2.0
https://segment.com/docs/connections/sources/catalog/libraries/website/javascript
MIT License
385 stars 128 forks source link

How to Cleanup trackForm/trackLink #1018

Open william-will-angi opened 6 months ago

william-will-angi commented 6 months ago

I am trying to use the trackForm/trackLink utilities but am not sure how to integrate it them in a React app.

const LinkComponent = (props) => {
  const ref = useRef()
  useEffect(()=>{
    window.analytics.trackLink(ref.current, {
      linkText: props.text
    })
    return () => {
      // What should I put here?
    }
  }, [props.text])
  return <a ref={ref}>{props.text}</a>
}

My concern is making sure only one event listener is ever assigned to the link, so if one of the props was to change, it doesn't receive an additional event listener.

Edit: I verified that calling trackLink on the same element multiple times will cause multiple track events to be fired.

silesky commented 6 months ago

@william-will-angi thank you for taking out an issue.

Without diving in too deeply, trackLink is targeted at vanilla JS environments (and not used very much) -- is there a reason you can't use the regular "analytics.track"?

william-will-angi commented 6 months ago

@silesky Thanks for the response.

We are currently using analytics.track, however in doing so we have to do logic similar to here to mimic the timeout functionality. It isn't terrible, but I was thinking it would be nice to re-use what already existed if possible. If trackLink is considered legacy now, we can continue using analytics.track