|
| 1 | +import { useCallback, useContext, useRef } from 'react'; |
| 2 | +import type { EvaluationContext } from '@openfeature/web-sdk'; |
| 3 | +import { OpenFeature } from '@openfeature/web-sdk'; |
| 4 | +import { Context } from '../common'; |
| 5 | + |
| 6 | +export type ContextMutationOptions = { |
| 7 | + /** |
| 8 | + * Mutate the default context instead of the domain scoped context applied at the `<OpenFeatureProvider/>`. |
| 9 | + * Note, if the `<OpenFeatureProvider/>` has no domain specified, the default is used. |
| 10 | + * See the {@link https://openfeature.dev/docs/reference/technologies/client/web/#manage-evaluation-context-for-domains|documentation} for more information. |
| 11 | + * @default false |
| 12 | + */ |
| 13 | + defaultContext?: boolean; |
| 14 | +}; |
| 15 | + |
| 16 | +export type ContextMutation = { |
| 17 | + /** |
| 18 | + * A function to set the desired context (see: {@link ContextMutationOptions} for details). |
| 19 | + * There's generally no need to await the result of this function; flag evaluation hooks will re-render when the context is updated. |
| 20 | + * This promise never rejects. |
| 21 | + * @param updatedContext |
| 22 | + * @returns Promise for awaiting the context update |
| 23 | + */ |
| 24 | + setContext: (updatedContext: EvaluationContext) => Promise<void>; |
| 25 | +}; |
| 26 | + |
| 27 | +/** |
| 28 | + * Get function(s) for mutating the evaluation context associated with this domain, or the default context if `defaultContext: true`. |
| 29 | + * See the {@link https://openfeature.dev/docs/reference/technologies/client/web/#targeting-and-context|documentation} for more information. |
| 30 | + * @param {ContextMutationOptions} options options for the generated function |
| 31 | + * @returns {ContextMutation} function(s) to mutate context |
| 32 | + */ |
| 33 | +export function useContextMutator(options: ContextMutationOptions = { defaultContext: false }): ContextMutation { |
| 34 | + const { domain } = useContext(Context) || {}; |
| 35 | + const previousContext = useRef<null | EvaluationContext>(null); |
| 36 | + |
| 37 | + const setContext = useCallback(async (updatedContext: EvaluationContext) => { |
| 38 | + if (previousContext.current !== updatedContext) { |
| 39 | + if (!domain || options?.defaultContext) { |
| 40 | + OpenFeature.setContext(updatedContext); |
| 41 | + } else { |
| 42 | + OpenFeature.setContext(domain, updatedContext); |
| 43 | + } |
| 44 | + previousContext.current = updatedContext; |
| 45 | + } |
| 46 | + }, [domain]); |
| 47 | + |
| 48 | + return { |
| 49 | + setContext, |
| 50 | + }; |
| 51 | +} |
0 commit comments