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 Parameter | Default type | Description |
|---|---|---|
T | - | The type of the value being resolved. |
F | null | The type returned by the fallback function. |
Parameters
| Parameter | Type | Description |
|---|---|---|
injectionId | ServiceIdentifier<T> | The service identifier (string, symbol, or constructor). |
onFallback? | (container: Container) => F | Optional 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));