Composition-api: fix: Cannot call `useContext` inside `onGlobalSetup` callback

Created on 13 Oct 2020  Âˇ  2Comments  Âˇ  Source: nuxt-community/composition-api

🐛 The bug

I'm trying to use onGlobalSetup to refactor some global injections I have currently in default layout setup function.

If I call useContext directly or any custom composition function try to call it while inside the onGlobalSetup, it throws an error with: Cannot read property 'context' of undefined

Failing here:

return {
  ...vm[globalNuxt].context, // 👈 Fails here
  route: computed(() => vm.$route),
  query: computed(() => vm.$route.query),
  from: computed(() => vm.$route.redirectedFrom),
  params: computed(() => vm.$route.params),
}

đŸ› ī¸ To reproduce
Steps to reproduce the behavior:

  1. Create a plugin file plugins/setup.js
  2. Call useContext inside a onGlobalSetup callback
import { defineNuxtPlugin, onGlobalSetup, useContext } from '@nuxtjs/composition-api';

export default defineNuxtPlugin(() => {
  onGlobalSetup(() => {
    useContext();
  });
});

Reproduction link:

https://codesandbox.io/s/nice-moser-xv3y1?file=/plugins/setup.js

🌈 Expected behaviour

From what I understand, onGlobalSetup is just running code inside the root component setup function. So it should be working with any composition API functions, not just provide.

Unless this is expected then I guess it should be documented maybe?

â„šī¸ Additional context

The reason I need to call useContext is that I have a few other composable functions that do call useContext, for cookie parsing and setting up a graphql client and various other stuff.

I would love to contribute to fix this, but I haven't figured out how you populate the globalNuxt values yet.

bug

All 2 comments

Thanks for the kind words @logaretm. Let me know if you'd like a code tour any time.

I suspect you're looking at the magic here:
https://github.com/nuxt-community/composition-api/blob/main/src/globals.ts#L1-L12

It gets populated by the module based on the settings the user has defined in their nuxt.config - though most people probably don't customise their global nuxt ($nuxt) to anything else.

Thank you, I love the work you are doing with this module and It has been an amazing experience so far.

Was this page helpful?
0 / 5 - 0 ratings