-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathuseFeatureFlagPayload.ts
More file actions
48 lines (42 loc) · 1.61 KB
/
useFeatureFlagPayload.ts
File metadata and controls
48 lines (42 loc) · 1.61 KB
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
import { ref, onMounted, onUnmounted } from 'vue'
import { usePostHog } from './usePostHog'
import type { JsonType } from 'posthog-js'
/**
* Get the payload of a feature flag
*
* @remarks
* This composable initializes with the current feature flag payload and automatically
* updates when PostHog feature flags are reloaded.
*
* **Server-Side Rendering (SSR) Behavior:**
* - During SSR, PostHog is typically not available or feature flags are not yet loaded
* - The returned ref will be `undefined` on the server side
* - The ref will be properly hydrated on the client side once PostHog initializes
* - Consider using a fallback value or `v-if` directive when rendering based on this value
*
* @example
* ```ts
* const payload = useFeatureFlagPayload('my-flag')
* ```
*
* @param flag - The feature flag key
* @returns A reactive ref containing the feature flag payload
*/
export function useFeatureFlagPayload(flag: string) {
const posthog = usePostHog()
const featureFlagPayload = ref<JsonType | undefined>(posthog?.getFeatureFlagResult?.(flag, { send_event: false })?.payload)
let unsubscribe: (() => void) | undefined
onMounted(() => {
if (!posthog) return
// Set initial value in case it wasn't available during setup
featureFlagPayload.value = posthog.getFeatureFlagResult(flag, { send_event: false })?.payload
// Update when feature flags are loaded
unsubscribe = posthog.onFeatureFlags?.(() => {
featureFlagPayload.value = posthog.getFeatureFlagResult(flag, { send_event: false })?.payload
})
})
onUnmounted(() => {
unsubscribe?.()
})
return featureFlagPayload
}