Skip to content
Open
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
5 changes: 5 additions & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,8 @@ export type { UseDecideConfig, UseDecideResult } from './useDecide';
export { useDecideForKeys } from './useDecideForKeys';
export type { UseDecideMultiResult } from './useDecideForKeys';
export { useDecideAll } from './useDecideAll';
export { useDecideAsync } from './useDecideAsync';
export type { UseDecideAsyncResult } from './useDecideAsync';
export { useDecideForKeysAsync } from './useDecideForKeysAsync';
export type { UseDecideMultiAsyncResult } 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
104 changes: 104 additions & 0 deletions src/hooks/useAsyncDecision.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* 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,
});
Comment on lines +23 to +53
Copy link

Copilot AI Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The async hooks rely on as UseDecide*AsyncResult type assertions when returning { result, error, isLoading }, which can mask violations of the intended discriminated union (e.g., accidentally returning isLoading: true with a non-null error after future refactors). Consider making useAsyncDecision return a discriminated union (or a helper that maps its internal state into the union) so TypeScript enforces the invariants and the hooks can return without assertions.

Copilot uses AI. Check for mistakes.

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;
}

// Store not ready — stay in loading
if (!hasConfig || userContext === null) {
setAsyncState({ result: emptyResult, error: null, isLoading: true });
Copy link

Copilot AI Apr 3, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

useAsyncDecision calls setAsyncState({ result: emptyResult, error: null, isLoading: true }) whenever the provider is not ready (!hasConfig || userContext === null). On initial mount (and on any store refresh while still not ready), this will schedule a state update even when the hook is already in the exact same loading state, causing an avoidable extra render. Consider using a functional setAsyncState with a guard (similar to the ready-path guard) so it returns prev when {isLoading:true,error:null,result===emptyResult} is already true.

Suggested change
setAsyncState({ result: emptyResult, error: null, isLoading: true });
setAsyncState((prev) => {
if (prev.isLoading && prev.error === null && prev.result === emptyResult) return prev;
return { result: emptyResult, error: null, isLoading: true };
});

Copilot uses AI. Check for mistakes.
return;
}

// Store is ready — fire async decision
let cancelled = false;
// Reset to loading before firing the async call.
// If already in the initial loading state, returns `prev` as-is to
// skip a redundant re-render on first mount.
setAsyncState((prev) => {
if (prev.isLoading && prev.error === null && prev.result === emptyResult) return prev;
return { result: emptyResult, error: null, isLoading: true };
});

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;
}
Loading
Loading