Skip to content
This repository was archived by the owner on Dec 5, 2024. It is now read-only.

Commit 9752a61

Browse files
committed
feat: add useContext helper function
`useContext` returns the Nuxt context without the need for a callback BREAKING CHANGE: `withContext` is now deprecated Closes #29
1 parent 4c15e10 commit 9752a61

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

README.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -117,18 +117,17 @@ const val2 = ssrRef(myExpensiveSetterFunction)
117117

118118
**Note**: Under the hood, `ssrRef` requires a key to ensure that the ref values match between client and server. If you have added `nuxt-composition-api` to your `buildModules`, this will be done automagically by an injected Babel plugin. If you need to do things differently, you can specify a key manually or add `nuxt-composition-api/babel` to your Babel plugins.
119119

120-
### withContext
120+
### useContext
121121

122-
You can access the Nuxt context more easily using `withContext`, which will immediately call the callback and pass it the Nuxt context.
122+
You can access the Nuxt context more easily using `useContext`, which will return the Nuxt context.
123123

124124
```ts
125-
import { defineComponent, ref, withContext } from 'nuxt-composition-api'
125+
import { defineComponent, ref, useContext } from 'nuxt-composition-api'
126126

127127
export default defineComponent({
128128
setup() {
129-
withContext(({ store }) => {
130-
store.dispatch('myAction')
131-
})
129+
const { store } = useContext()
130+
store.dispatch('myAction')
132131
},
133132
})
134133
```

src/context.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,20 @@ interface ContextCallback {
55
(context: Context): void
66
}
77

8+
/**
9+
* @deprecated
10+
* Recommend using `useContext` instead
11+
*/
812
export const withContext = (callback: ContextCallback) => {
913
const vm = getCurrentInstance()
1014
if (!vm) throw new Error('This must be called within a setup function.')
1115

1216
callback(vm.$nuxt.context)
1317
}
18+
19+
export const useContext = () => {
20+
const vm = getCurrentInstance()
21+
if (!vm) throw new Error('This must be called within a setup function.')
22+
23+
return vm.$nuxt.context
24+
}

0 commit comments

Comments
 (0)