Skip to content

Commit

Permalink
feat(createInjectionState): add defaultValue option
Browse files Browse the repository at this point in the history
  • Loading branch information
melishev committed Apr 1, 2024
1 parent 1558cd2 commit e288c11
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
26 changes: 26 additions & 0 deletions packages/shared/createInjectionState/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,29 @@ const [useProvideCounterStore, useCounterStore] = createInjectionState((initialV
return { count, double, increment }
}, { injectionKey: CounterStoreKey })
```

## Provide a custom default value

```ts
// useCounterStore.ts
import { computed, ref } from 'vue'
import { createInjectionState } from '@vueuse/core'

// custom defaultValue
const CounterStoreDefaultValue = undefined

const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => {
// state
const count = ref(initialValue)

// getters
const double = computed(() => count.value * 2)

// actions
function increment() {
count.value++
}

return { count, double, increment }
}, { defaultValue: CounterStoreDefaultValue })
```
9 changes: 7 additions & 2 deletions packages/shared/createInjectionState/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ export interface CreateInjectionStateOptions<Return> {
* Custom injectionKey for InjectionState
*/
injectionKey?: string | InjectionKey<Return>
/**
* Default value for the InjectionState
*/
defaultValue: Return | (() => Return)
}

/**
Expand All @@ -18,13 +22,14 @@ export interface CreateInjectionStateOptions<Return> {
export function createInjectionState<Arguments extends Array<any>, Return>(
composable: (...args: Arguments) => Return,
options?: CreateInjectionStateOptions<Return>,
): readonly [useProvidingState: (...args: Arguments) => Return, useInjectedState: () => Return | undefined] {
): readonly [useProvidingState: (...args: Arguments) => Return, useInjectedState: () => Return | (() => Return) | undefined] {
const key: string | InjectionKey<Return> = options?.injectionKey || Symbol(composable.name || 'InjectionState')
const defaultValue = options?.defaultValue
const useProvidingState = (...args: Arguments) => {
const state = composable(...args)
provideLocal(key, state)
return state
}
const useInjectedState = () => injectLocal(key)
const useInjectedState = () => injectLocal(key, defaultValue)
return [useProvidingState, useInjectedState]
}

0 comments on commit e288c11

Please sign in to comment.