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
103 changes: 103 additions & 0 deletions src/hooks/useDecideAllAsync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* 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 { OptimizelyDecision } from '@optimizely/optimizely-sdk';

import { useOptimizelyContext } from './useOptimizelyContext';
import { useProviderState } from './useProviderState';
import { useStableArray } from './useStableArray';
import type { UseDecideConfig } from './useDecide';
import type { UseDecideMultiAsyncResult } from './useDecideForKeysAsync';

/**
* Returns feature flag decisions for all flags using the async
* `decideAllAsync` API. Required for CMAB (Contextual Multi-Armed Bandit) support.
*
* Client-side only — `decideAllAsync` returns a Promise which cannot resolve
* during server render.
*
* @param config - Optional configuration (decideOptions)
*/
export function useDecideAllAsync(config?: UseDecideConfig): UseDecideMultiAsyncResult {
const { store, client } = useOptimizelyContext();
const decideOptions = useStableArray(config?.decideOptions);
const state = useProviderState(store);

// --- Forced decision subscription — any flag key ---
const [fdVersion, setFdVersion] = useState(0);
useEffect(() => {
return store.subscribeAllForcedDecisions(() => setFdVersion((v) => v + 1));
}, [store]);

// --- Async decision state ---
const [asyncState, setAsyncState] = useState<{
decisions: Record<string, OptimizelyDecision> | Record<string, never>;
error: Error | null;
isLoading: boolean;
}>({ decisions: {} as Record<string, never>, error: null, isLoading: true });

// --- Async decision effect ---
useEffect(() => {
const { userContext, error } = state;
const hasConfig = client.getOptimizelyConfig() !== null;

// Store-level error — no async call needed
if (error) {
setAsyncState({ decisions: {} as Record<string, never>, error, isLoading: false });
return;
}

// Store not ready — stay in loading
if (!hasConfig || userContext === null) {
setAsyncState({ decisions: {} as Record<string, never>, error: null, isLoading: true });
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 && Object.keys(prev.decisions).length === 0) return prev;
return { decisions: {} as Record<string, never>, error: null, isLoading: true };
});

userContext.decideAllAsync(decideOptions).then(
(decisions) => {
if (!cancelled) {
setAsyncState({ decisions, error: null, isLoading: false });
}
},
(err) => {
if (!cancelled) {
setAsyncState({
decisions: {} as Record<string, never>,
error: err instanceof Error ? err : new Error(String(err)),
isLoading: false,
});
}
}
);

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

return asyncState as UseDecideMultiAsyncResult;
}
Loading
Loading