|
| 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 | + * Apply changes to 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 | + */ |
| 11 | + default?: boolean; |
| 12 | +}; |
| 13 | + |
| 14 | +export type ContextMutation = { |
| 15 | + /** |
| 16 | + * A function to set the desired context (see: {@link ContextMutationOptions} for details). |
| 17 | + * @param updatedContext |
| 18 | + * @returns |
| 19 | + */ |
| 20 | + setContext: (updatedContext: EvaluationContext) => Promise<void> |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * Get function(s) for mutating the evaluation context associated with this domain, or the default context if `global: true`. |
| 25 | + * @param {ContextMutationOptions} options options for the generated function |
| 26 | + * @returns {ContextMutation}function to mutate context |
| 27 | + */ |
| 28 | +export function useContextMutator(options: ContextMutationOptions = {}): ContextMutation { |
| 29 | + const { domain } = useContext(Context) || {}; |
| 30 | + const previousContext = useRef<null | EvaluationContext>(null); |
| 31 | + |
| 32 | + const setContext = useCallback(async (updatedContext: EvaluationContext) => { |
| 33 | + if (previousContext.current !== updatedContext) { |
| 34 | + if (!domain || options?.default) { |
| 35 | + OpenFeature.setContext(updatedContext); |
| 36 | + } else { |
| 37 | + OpenFeature.setContext(domain, updatedContext); |
| 38 | + } |
| 39 | + previousContext.current = updatedContext; |
| 40 | + } |
| 41 | + }, [domain]); |
| 42 | + |
| 43 | + return { |
| 44 | + setContext, |
| 45 | + }; |
| 46 | +} |
0 commit comments