PostHog / posthog-js-lite

Reimplementation of posthog-js to be as light and modular as possible.
https://posthog.com/docs/libraries
MIT License
70 stars 36 forks source link

Don't complain about "initAsync called twice" when hot reloading #114

Closed statico closed 9 months ago

statico commented 1 year ago

Is your feature request related to a problem?

Similar to #113 — every time my React Native app is loaded, reloaded, or the base layout changes (we're using expo-router), PostHog throws up a giant warning:

PostHog.initAsync called twice with the same apiKey. The first instance will be used.

It would be nice to disable this message when __DEV__ is true.

Recoil, a state management library for React, had a similar behavior with singletons and hot reloading and solved this by allowing developers to add a RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED=false setting: https://github.com/facebookexperimental/Recoil/issues/733

Describe the solution you'd like

Some kind of setting, maybe in PostHogProvider, like dangerouslyIgnoreReinitialization or iKnowWhatImDoing={__DEV__} or something, that removes this warning.

Describe alternatives you've considered

Related sub-libraries

Additional context

<3

hikchoi commented 1 year ago

seconding this. pretty harmless, but it makes it hard to read other logs that I actually want to read :(

@statico are you still patching the package on your end or have you found any other workarounds?

statico commented 1 year ago

@hikchoi Yep, still patching this and a few other messages. Previously with patch-package, now with pnpm's built-in patcher.

marandaneto commented 1 year ago

Maybe the solution here is to patch the Router and not call PostHog.initAsync again when a hot reload just happened, you can do that via env. var. (similar to 113) or a global variable that survives hot reload.

We already do that here but if the whole Provider gets recreated, this field is also gone, the solution would be to depend on an external global variable.

edumana commented 10 months ago

I was getting this error and solved it by putting PH provider at the very top of the RootLayout, and moving everything to a new App child component. I had some auth states changing which were causing PH provider to reload. So my app now looks like this:

const RootLayout = () => {
  return (
      <PostHogProvider
        apiKey={process.env.EXPO_PUBLIC_POSTHOG_API_KEY}
        options={{ host: process.env.EXPO_PUBLIC_POSTHOG_HOST}}
      >
        <App /> // <------ all child components with changing states 
      </PostHogProvider>
  );
};

export default RootLayout;
marandaneto commented 9 months ago

Closed by https://github.com/PostHog/posthog-js-lite/pull/179 The warning is removed since it's not useful anyway, you can still do this to spare the recreation bits.