-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcloud-url.ts
52 lines (40 loc) · 1.2 KB
/
cloud-url.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useState, useEffect, useRef } from "react"
import ExecutionEnvironment from "@docusaurus/ExecutionEnvironment"
import customFields from "../config/customFields"
type WindowWithPosthog = Window & {
posthog: {
get_distinct_id: () => string
}
}
const MAX_ATTEMPTS = 3
export const useCloudUrl = () => {
const [url, setUrl] = useState(customFields.cloudUrl)
const attempts = useRef(1)
useEffect(() => {
let interval: NodeJS.Timeout
if (ExecutionEnvironment.canUseDOM) {
console.log("Running in browser environment")
const win = window as unknown as WindowWithPosthog
interval = setInterval(() => {
if (attempts.current >= MAX_ATTEMPTS) {
clearInterval(interval)
}
attempts.current += 1
const hasPosthog = Boolean(win.posthog?.get_distinct_id)
if (hasPosthog) {
const id = win.posthog.get_distinct_id()
if (!url.includes(`#id=${id}`)) {
setUrl(`${url}#id=${id}`)
}
clearInterval(interval)
}
}, 200)
} else {
console.log("Not running in browser environment")
}
return () => {
clearInterval(interval)
}
}, [url])
return url
}