How to read a feature flag
This guide shows you how to read the resolved bucket of a feature flag in your application. You need a feature flag in your project first, either from the dashboard or defined in SDK code.
Which accessor you pick decides when the visitor enters the test, so read About feature flag allocation before you choose.
1. Choose an accessor
Each accessor returns a different value, and they differ in whether a read resolves the feature flag. A read that resolves the feature flag commits the visitor to a bucket and reports the decision.
| API | Returns | Does a read resolve the feature flag? |
|---|---|---|
useFeature / getFeature | () => Promise<bucket> | Only when you call the function that it returns |
useFeatureResult / getFeatureResult | { id, bucket }, and undefined until it resolves | Yes, as soon as the component renders |
useFeatureEnabled / getFeatureEnabled | boolean | undefined, the dashboard Enabled setting | No |
client.features.listStore | Every registered feature flag, each with an isResolved property | No |
client.features.getById(id) | A store that holds one feature flag | No |
Some decisions must wait for data that you do not have yet, such as a cart, a quote, or
the profile of a signed-in user. For those, use useFeature or getFeature. Call the
function they return after the data arrives.
2. Read the bucket
The bucket is what your site receives. A Boolean feature flag gives true or false. A
Text feature flag gives the value of one variant, or false for the control group.
import { useFeatureResult } from '@picked/react/hooks'
function MyComponent() {
// { id, bucket }, or undefined until the feature flag resolves.
const result = useFeatureResult('hero')
return (
<div>
{result?.bucket === false && <p>Control</p>}
{result?.bucket === 'hero-a' && <p>Hero A</p>}
{result?.bucket === 'hero-b' && <p>Hero B</p>}
</div>
)
}<script lang="ts">
import { getFeatureResult } from '@picked/svelte/hooks'
// A store that holds { id, bucket }, or undefined until the feature flag resolves.
const result = getFeatureResult('hero')
</script>
{#if $result?.bucket === false}
<p>Control</p>
{:else if $result?.bucket === 'hero-a'}
<p>Hero A</p>
{:else if $result?.bucket === 'hero-b'}
<p>Hero B</p>
{/if}3. Read it without a framework
The event bus works with any framework, and with none:
import { createClient } from 'picked'
const client = createClient({
/* Put your client options here. */
})
client.eventBus.watch((event) => {
if (event.type === 'feature_decide' && event.feature.id === 'my-feature') {
console.log(event.feature) // { id: 'my-feature', key: 'v1', bucket: 'hero-a' }
}
})feature_decide fires only when the SDK makes a new decision. A visitor who returns
restores the decision from storage and fires nothing, so watch
client.features.listStore when you need the current state instead.
Related
- About feature flag allocation — when the visitor enters the test.
- SDK feature flags — the definition shape and the overrides.
