Skip to content

Function: useOptionalInjection()

ts
function useOptionalInjection<T, F>(injectionId: ServiceIdentifier<T>, onFallback?: (container: Container) => F): T | F;

Defined in: src/wirestate-react/injection/use-optional-injection.ts:32

Safely resolves a value from the container, returning a fallback or null if not bound.

Type Parameters

Type ParameterDefault typeDescription
T-The type of the value being resolved.
FnullThe type returned by the fallback function.

Parameters

ParameterTypeDescription
injectionIdServiceIdentifier<T>The service identifier (string, symbol, or constructor).
onFallback?(container: Container) => FOptional function called to provide a value if the token is not bound.

Returns

T | F

The resolved value, the result of the fallback function, or null when no fallback is provided.

Remarks

Unlike useInjection, this hook does not throw if the dependency is missing from the container.

Example

tsx
const logger = useOptionalInjection(FileLogger, (container) => container.get(ConsoleLoggerService));