馃摎 What are you trying to do? Please describe.
I am trying to call useContext() within a function that is inside setup
馃攳 What have you tried?
<script lang="ts">
import { defineComponent } from '@nuxtjs/composition-api'
import useAuth from '@/compositions/auth'
export default defineComponent({
layout: 'auth',
setup() {
return useAuth()
},
})
</script>
@/compositions/auth
import { useContext, reactive, toRefs } from '@nuxtjs/composition-api'
export default function useAuth() {
const state = reactive({
foo: '',
})
async function bar() {
const { app } = useContext() // this throws the error: This must be called within a setup function.
}
return {
...toRefs(state),
bar,
}
}
Am I missing something, how should I approah this?
You have to call useContext inside the setup function you call it in a function inside the setup function. Your bar function will be called on a DOM event so not while running the setup function.
Try:
import { useContext, reactive, toRefs } from '@nuxtjs/composition-api'
export default function useAuth() {
const state = reactive({
foo: '',
})
const { app } = useContext()
async function bar() {
console.log(app)
}
return {
...toRefs(state),
bar,
}
}
Thank you!
Most helpful comment
You have to call
useContextinside the setup function you call it in a function inside the setup function. Your bar function will be called on a DOM event so not while running the setup function.Try: