UNPKG

solid-posthog

Version:

Allows you to PostHog within SolidJS

91 lines (86 loc) 2.2 kB
import posthog2 from 'posthog-js'; import { createContext, createSignal, createMemo, onMount, useContext } from 'solid-js'; import { createComponent } from 'solid-js/web'; // src/context/PostHogContext.ts var PostHogContext = createContext({ client: posthog2 }); // src/utils/object-utils.ts function isDeepEqual(obj1, obj2, visited = /* @__PURE__ */ new WeakMap()) { if (obj1 === obj2) { return true; } if (typeof obj1 !== "object" || obj1 === null || typeof obj2 !== "object" || obj2 === null) { return false; } if (visited.has(obj1) && visited.get(obj1) === obj2) { return true; } visited.set(obj1, obj2); const keys1 = Object.keys(obj1); const keys2 = Object.keys(obj2); if (keys1.length !== keys2.length) { return false; } for (const key of keys1) { if (!keys2.includes(key)) { return false; } if (!isDeepEqual(obj1[key], obj2[key], visited)) { return false; } } return true; } // src/context/PostHogProvider.tsx function PostHogProvider({ children, client, apiKey, options }) { const [previousInitialization, setPreviousInitialization] = createSignal(null); const postHogJs = createMemo(() => { if (client) { if (options) { return client; } } if (apiKey) { return posthog2; } return posthog2; }, [client, apiKey, JSON.stringify(options)]); onMount(() => { if (client) return; const prev = previousInitialization(); if (!prev) { if (posthog2.__loaded) ; posthog2.init(apiKey, options); setPreviousInitialization({ apiKey, options: options ?? {} }); } else { if (apiKey !== prev.apiKey) ; if (options && !isDeepEqual(options, prev.options)) { posthog2.set_config(options); } setPreviousInitialization({ apiKey, options: options ?? {} }); } }); return createComponent(PostHogContext.Provider, { get value() { return { client: postHogJs() }; }, children }); } var usePostHog = () => { const { client } = useContext(PostHogContext); return client; }; export { PostHogContext, PostHogProvider, usePostHog };