Skip to content

Commit

Permalink
feature(composable): create utility composable useHybridInject
Browse files Browse the repository at this point in the history
  • Loading branch information
CachedaCodes committed Feb 20, 2024
1 parent 7f28d20 commit cb97e3e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/x-components/src/composables/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export * from './use-on-display';
export * from './use-store';
export * from './use-state';
export * from './use-getter';
export * from './use-hybrid-inject';
26 changes: 26 additions & 0 deletions packages/x-components/src/composables/use-hybrid-inject.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { computed, ComputedRef, inject } from 'vue';

/**
* Function to use a hybrid inject, which allows to inject a value provided by the regular provide
* of vue or by the XProvide decorator.
*
* @param key - The key of the value to inject.
* @param defaultValue - The default value to use if the value is not provided.
* @returns The computed value of the injected value.
*/
export function useHybridInject<SomeValue>(
key: string,
defaultValue?: SomeValue
): ComputedRef<SomeValue | undefined> {
type WrappedValue = { value: SomeValue };

return computed<SomeValue | undefined>(() => {
const injectedValue = defaultValue
? inject<SomeValue | WrappedValue>(key, defaultValue)
: inject<SomeValue | WrappedValue>(key);

return injectedValue && typeof injectedValue === 'object' && 'value' in injectedValue
? injectedValue.value
: injectedValue;
});
}

0 comments on commit cb97e3e

Please sign in to comment.