menu

Questions & Answers

Nuxt - Cannot call useContext() inside watch() callback

I'm using @nuxtjs/composition-api version 0.33.1 with Nuxt 2, and my component looks like this:

import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api';

export default defineComponent({
  setup () {
    const route = useRoute();

    // Other code...

    watch(() => route.value.query, () => {
      const { $axios } = useContext();
    });

    // Other code...
  }
});

As you can see, I'm trying to do something when the route.value.query changes. However, this gives me the error:

Error: This must be called within a setup function.
    at useContext (index.mjs?9a99:220:1)
    at eval (search.vue?9447:34:1)
    at invokeWithErrorHandling (vue.common.dev.js?4650:3634:1)
    at call (vue.common.dev.js?4650:3271:1)
    at watcher.run (vue.common.dev.js?4650:3375:1)
    at flushSchedulerQueue (vue.common.dev.js?4650:3140:1)
    at Array.eval (vue.common.dev.js?4650:3760:1)
    at flushCallbacks (vue.common.dev.js?4650:3682:1)

Did I miss something? How can I call useContext() inside the callback of watch()? Or is it not possible at all?

Answers(1) :

I found this answer in github. the solution suggests to add the latest version of the nuxt composition api.

Comments:
2023-01-11 09:30:03
I have the latest version, 0.33.1.