Composition-api: help: calling useContext inside functions throws error

Created on 12 Jan 2021  路  2Comments  路  Source: nuxt-community/composition-api

馃摎 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?

Most helpful comment

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,
  }
}

All 2 comments

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!

Was this page helpful?
0 / 5 - 0 ratings