Skip to content

Commit

Permalink
feat(core): add sideEffects flag and enhance useContext functionality (
Browse files Browse the repository at this point in the history
…#568)

* feat(core): add sideEffects flag and enhance useContext functionality

* feat(core): include InjectionKey in createContext return type
  • Loading branch information
productdevbook authored Nov 18, 2024
1 parent 31a7317 commit 5bfc675
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"bugs": {
"url": "https://github.com/oku-ui/primitives/issues"
},

"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
Expand Down
17 changes: 10 additions & 7 deletions packages/core/src/hooks/createContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,20 @@ import { inject, type InjectionKey, provide } from 'vue'
* @see https://vueuse.org/createInjectionState
*
*/
export function createContext<T>(contextName: string, defaultValue: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T]
export function createContext<T>(contextName: string): readonly [useProvidingState: (state: T) => void, useContext: (consumerName: string) => T]
export function createContext<T>(contextName: string, defaultValue?: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T] {
const key: string | InjectionKey<T> = Symbol(contextName)
export function createContext<T>(contextName: string, defaultValue: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T, key: InjectionKey<T>]
export function createContext<T>(contextName: string): readonly [useProvidingState: (state: T) => void, useContext: (consumerName: string) => T, key: InjectionKey<T>]
export function createContext<T>(contextName: string, defaultValue?: T): readonly [useProvidingState: (state: T) => void, useContext: (consumerName?: string) => T, key: InjectionKey<T>] {
const key: InjectionKey<T> = Symbol(contextName)

const provideContext = (state: T) => {
provide(key, state)
}

const useContext = (consumerName?: string) => {
const state = inject(key, defaultValue)
const useContext = (consumerName?: string, value?: any) => {
const state = inject(key, value ?? defaultValue)

if (state === null)
return state as any

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

return [provideContext, useContext]
return [provideContext, useContext, key]
}

0 comments on commit 5bfc675

Please sign in to comment.