UNPKG

solid-posthog

Version:

Allows you to PostHog within SolidJS

96 lines (91 loc) 2.31 kB
// src/context/PostHogContext.ts import posthog from "posthog-js"; import { createContext } from "solid-js"; var PostHogContext = createContext({ client: posthog }); // src/context/PostHogProvider.tsx import posthog2 from "posthog-js"; import { createMemo, createSignal, onMount } from "solid-js"; // 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 (apiKey) { } 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 <PostHogContext.Provider value={{ client: postHogJs() }}>{children}</PostHogContext.Provider>; } // src/hooks/usePostHog.ts import { useContext } from "solid-js"; var usePostHog = () => { const { client } = useContext(PostHogContext); return client; }; export { PostHogContext, PostHogProvider, usePostHog };