Skip to content

Commit 5bfc675

Browse files
feat(core): add sideEffects flag and enhance useContext functionality (#568)
* feat(core): add sideEffects flag and enhance useContext functionality * feat(core): include InjectionKey in createContext return type
1 parent 31a7317 commit 5bfc675

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

packages/core/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
"bugs": {
1414
"url": "https://github.com/oku-ui/primitives/issues"
1515
},
16-
16+
"sideEffects": false,
1717
"exports": {
1818
".": {
1919
"types": "./dist/index.d.ts",

packages/core/src/hooks/createContext.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,20 @@ import { inject, type InjectionKey, provide } from 'vue'
66
* @see https://vueuse.org/createInjectionState
77
*
88
*/
9-
export function createContext<T>(contextName: string, defaultValue: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T]
10-
export function createContext<T>(contextName: string): readonly [useProvidingState: (state: T) => void, useContext: (consumerName: string) => T]
11-
export function createContext<T>(contextName: string, defaultValue?: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T] {
12-
const key: string | InjectionKey<T> = Symbol(contextName)
9+
export function createContext<T>(contextName: string, defaultValue: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T, key: InjectionKey<T>]
10+
export function createContext<T>(contextName: string): readonly [useProvidingState: (state: T) => void, useContext: (consumerName: string) => T, key: InjectionKey<T>]
11+
export function createContext<T>(contextName: string, defaultValue?: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T, key: InjectionKey<T>] {
12+
const key: InjectionKey<T> = Symbol(contextName)
1313

1414
const provideContext = (state: T) => {
1515
provide(key, state)
1616
}
1717

18-
const useContext = (consumerName?: string) => {
19-
const state = inject(key, defaultValue)
18+
const useContext = (consumerName?: string, value?: any) => {
19+
const state = inject(key, value ?? defaultValue)
20+
21+
if (state === null)
22+
return state as any
2023

2124
if (!state) {
2225
throw new Error(`\`${consumerName}\` must be used within \`${contextName}\``)
@@ -25,5 +28,5 @@ export function createContext<T>(contextName: string, defaultValue?: T): readonl
2528
return state
2629
}
2730

28-
return [provideContext, useContext]
31+
return [provideContext, useContext, key]
2932
}

0 commit comments

Comments
 (0)