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 2, 2024
1 parent 1558cd2 commit 031ffcf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
23 changes: 23 additions & 0 deletions packages/shared/createInjectionState/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,26 @@ 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'

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: 0 })
```
7 changes: 6 additions & 1 deletion 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
}

/**
Expand All @@ -20,11 +24,12 @@ export function createInjectionState<Arguments extends Array<any>, Return>(
options?: CreateInjectionStateOptions<Return>,
): readonly [useProvidingState: (...args: Arguments) => Return, useInjectedState: () => 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 031ffcf

Please sign in to comment.