Home > Enterprise >  Nuxt - Cannot call useContext() inside watch() callback
Nuxt - Cannot call useContext() inside watch() callback

Time:01-11

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?

CodePudding user response:

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

CodePudding user response:

As confirmed by the developer of the package, it is not possible to have useContext() in the watcher callback.

The workaround is to call useContext() first, then use its returned values in the callback.

import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api';
export default defineComponent({
  setup () {
    const route = useRoute();
    // Other code...

    const { $axios } = useContext();
    watch(() => route.value.query, () => {
      // use $axios here
    });
    // Other code...
  }
});
  • Related