#pinia custom plugin undefined

1 messages · Page 1 of 1 (latest)

brisk meadow
#

Hey there i have a custom fetch function from the docs https://nuxt.com/docs/guide/recipes/custom-usefetch but when declaring it inside the global store context of a pinia store its undefined, in the function scope it is not. But i dont really wanna call the useNuxtApp() composable everytime I fetch:

export const useUserStore = defineStore("userStore", (context) => {
// Global Store scope
  const nuxtApp = useNuxtApp()
  console.log(nuxtApp.$apiFetch); // undefined

  async function Fetch() {
// function scope
    const nuxtApp = useNuxtApp()

    await nuxtApp.$apiFetch() // working
  }
});

Do you have any regards why?
Thanks!

#

Apparently its not initialized yet, even tho i named the plugin 01.apiFetch.ts - any solutions to this?

const nuxtApp = useNuxtApp()
console.log(nuxtApp.$apiFetch);

nextTick(() => {
  const nuxtApp = useNuxtApp()
  console.log(nuxtApp.$apiFetch);
  
  nextTick(() => {
    const nuxtApp = useNuxtApp()
    console.log(nuxtApp.$apiFetch);
    
    nextTick(() => {
      const nuxtApp = useNuxtApp()
      console.log(nuxtApp.$apiFetch);
    })
  })
})
undefined
undefined
undefined
async ƒ $fetch2(request, options) {
  const r = await $fetchRaw(request, options);
  return r._data;
}
verbal flare
#

Configure the plugin dependency option if you want to initialize the plugin after it is loaded I.e. dependsOn: ['pinia']

#

Otherwise just define a composable and use that for simplicity.

brisk meadow
#

Thanks for the answer, unfortuantely its the other way around, pinia should wait for the plugin. I tried out your solution and $apiFetch is undefined
I havent found anything to let pinia wait on other plugins

verbal flare
#

Have you tried the more simplistic avenue of creating a composable? If it needs to be a plugin to, just provide the api from the composable.