counterscale icon indicating copy to clipboard operation
counterscale copied to clipboard

Provide way to access client initialization state

Open wesbos opened this issue 8 months ago • 1 comments

Currently if the Counterscale.init() function is run twice, it throws and error.

Sometimes code runs twice - like in react strict mode. So if it's already initialized, it would be nice to do one of these:

  1. It just returns early. Maybe silently?
  2. Provide the a function that will return the client, or a boolean from the GLOBALS variable here: https://github.com/benvinegar/counterscale/blob/main/packages/tracker/src/index.ts#L7 so ew can conditionally run init()

Also while we're talking about the client code - is it possible to also return early if history doesn't exist? Helpful for not breaking server rendered code. Currently doing this:

let isInitialized = false;
const isClient = typeof window !== 'undefined';

export function analytics() {
  if (isClient && !isInitialized) {
    Counterscale.init({
      siteId: `wesbos-${import.meta.env.DEV ? '-dev' : ''}`,
      reporterUrl: 'https://nunyabiznass.wesbos.com/collect',
    });
    isInitialized = true;
  }
}

wesbos avatar May 02 '25 15:05 wesbos

I did rush this out pretty fast ... this is the most detailed feedback I've gotten yet. Super helpful, thanks @wesbos. 🙏

benvinegar avatar May 03 '25 15:05 benvinegar

Hey @wesbos - took a stab at this and would love any thoughts/feedback you have on the added methods 🙏 https://github.com/benvinegar/counterscale/pull/205

stordahl avatar Jul 26 '25 04:07 stordahl