Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
export { useOptimizelyClient } from './useOptimizelyClient';
export { useOptimizelyUserContext } from './useOptimizelyUserContext';
export type { UseOptimizelyUserContextResult } from './useOptimizelyUserContext';
export type { UseDecideConfig, UseDecideResult, UseDecideMultiResult } from './types';
export { useDecide } from './useDecide';
export type { UseDecideConfig, UseDecideResult } from './useDecide';
export { useDecideForKeys } from './useDecideForKeys';
export type { UseDecideMultiResult } from './useDecideForKeys';
export { useDecideAll } from './useDecideAll';
export { useDecideAsync } from './useDecideAsync';
export { useDecideForKeysAsync } from './useDecideForKeysAsync';
export { useDecideAllAsync } from './useDecideAllAsync';
15 changes: 12 additions & 3 deletions src/hooks/testUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ export const MOCK_DECISIONS: Record<string, OptimizelyDecision> = {
* Creates a mock OptimizelyUserContext with all methods stubbed.
* Override specific methods via the overrides parameter.
*/
export function createMockUserContext(
overrides?: Partial<Record<string, unknown>>,
): OptimizelyUserContext {
export function createMockUserContext(overrides?: Partial<Record<string, unknown>>): OptimizelyUserContext {
return {
getUserId: vi.fn().mockReturnValue('test-user'),
getAttributes: vi.fn().mockReturnValue({}),
Expand All @@ -66,6 +64,17 @@ export function createMockUserContext(
}
return result;
}),
decideAsync: vi.fn().mockResolvedValue(MOCK_DECISION),
decideAllAsync: vi.fn().mockResolvedValue(MOCK_DECISIONS),
decideForKeysAsync: vi.fn().mockImplementation((keys: string[]) => {
const result: Record<string, OptimizelyDecision> = {};
for (const key of keys) {
if (MOCK_DECISIONS[key]) {
result[key] = MOCK_DECISIONS[key];
}
}
return Promise.resolve(result);
}),
setForcedDecision: vi.fn().mockReturnValue(true),
getForcedDecision: vi.fn(),
removeForcedDecision: vi.fn().mockReturnValue(true),
Expand Down
31 changes: 31 additions & 0 deletions src/hooks/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Copyright 2026, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { OptimizelyDecideOption, OptimizelyDecision } from '@optimizely/optimizely-sdk';

export interface UseDecideConfig {
decideOptions?: OptimizelyDecideOption[];
}

export type UseDecideResult =
| { isLoading: true; error: null; decision: null }
| { isLoading: false; error: Error; decision: null }
| { isLoading: false; error: null; decision: OptimizelyDecision };

export type UseDecideMultiResult =
| { isLoading: true; error: null; decisions: Record<string, never> }
| { isLoading: false; error: Error; decisions: Record<string, never> }
| { isLoading: false; error: null; decisions: Record<string, OptimizelyDecision> };
102 changes: 102 additions & 0 deletions src/hooks/useAsyncDecision.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/**
* Copyright 2026, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { useEffect, useState } from 'react';
import type { OptimizelyUserContext } from '@optimizely/optimizely-sdk';

import type { Client } from '@optimizely/optimizely-sdk';
import type { ProviderState } from '../provider/index';

interface AsyncState<TResult> {
result: TResult;
error: Error | null;
isLoading: boolean;
}

/**
* Shared async decision state machine used by useDecideAsync,
* useDecideForKeysAsync, and useDecideAllAsync.
*
* Handles: loading state, error propagation, cancellation of stale promises,
* and redundant re-render avoidance on first mount.
*
* @param state - Provider state from useProviderState
* @param client - Optimizely client instance
* @param fdVersion - Forced decision version counter (triggers re-evaluation)
* @param emptyResult - Default/empty result value (null for single, {} for multi)
* @param execute - Callback that performs the async SDK call
*/
export function useAsyncDecision<TResult>(
state: ProviderState,
client: Client,
fdVersion: number,
emptyResult: TResult,
execute: (userContext: OptimizelyUserContext) => Promise<TResult>
): AsyncState<TResult> {
const [asyncState, setAsyncState] = useState<AsyncState<TResult>>({
result: emptyResult,
error: null,
isLoading: true,
});

useEffect(() => {
const { userContext, error } = state;
const hasConfig = client.getOptimizelyConfig() !== null;

// Store-level error — no async call needed
if (error) {
setAsyncState({ result: emptyResult, error, isLoading: false });
return;
}

// Ensure loading state (skip if already loading to avoid re-render)
setAsyncState((prev) => {
if (prev.isLoading) return prev;
return { result: emptyResult, error: null, isLoading: true };
});

// Store not ready — wait for config/user context
if (!hasConfig || userContext === null) {
return;
}

// Store is ready — fire async decision
let cancelled = false;

execute(userContext).then(
(result) => {
if (!cancelled) {
setAsyncState({ result, error: null, isLoading: false });
}
},
(err) => {
if (!cancelled) {
setAsyncState({
result: emptyResult,
error: err instanceof Error ? err : new Error(String(err)),
isLoading: false,
});
}
}
);

return () => {
cancelled = true;
};
}, [state, fdVersion, client, execute, emptyResult]);

return asyncState;
}
12 changes: 1 addition & 11 deletions src/hooks/useDecide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,10 @@
*/

import { useEffect, useMemo, useState } from 'react';
import type { OptimizelyDecideOption, OptimizelyDecision } from '@optimizely/optimizely-sdk';

import { useOptimizelyContext } from './useOptimizelyContext';
import { useProviderState } from './useProviderState';
import { useStableArray } from './useStableArray';

export interface UseDecideConfig {
decideOptions?: OptimizelyDecideOption[];
}

export type UseDecideResult =
| { isLoading: true; error: null; decision: null }
| { isLoading: false; error: Error; decision: null }
| { isLoading: false; error: null; decision: OptimizelyDecision };
import type { UseDecideConfig, UseDecideResult } from './types';

/**
* Returns a feature flag decision for the given flag key.
Expand Down
3 changes: 1 addition & 2 deletions src/hooks/useDecideAll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useOptimizelyContext } from './useOptimizelyContext';
import { useProviderState } from './useProviderState';
import { useStableArray } from './useStableArray';
import type { UseDecideConfig } from './useDecide';
import type { UseDecideMultiResult } from './useDecideForKeys';
import type { UseDecideConfig, UseDecideMultiResult } from './types';

/**
* Returns feature flag decisions for all flags.
Expand Down
Loading
Loading