juancho perez
juancho perez

Reputation: 45

nuxt3 A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function

I am starting in nuxt 3, I am working on a project in which we have centralized what is the useFetch in a composable in which we have decided to place

const config = useRuntimeConfig();

to use environment variables but we get the following error

[nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function

when the composable is called from a store of pinia

here is the code of the composable

import { UseFetchOptions } from "nuxt/app";
const config = useRuntimeConfig();
export function useApiFetch<T>(path: string, options: UseFetchOptions<T> = {}) {
 return useFetch(config.public.BASE_API_URL + path,{
    ...options,
  });
}

here where we use it for example

export const useAuthStore = defineStore("auth", () => {
  const user = ref<User | null>(null);
  const isLoggedIn = computed(() => !!user.value);
  async function logout() {
    await useApiFetch("/logout", { method: "POST" });
    user.value = null;
    token.value = null;
    navigateTo("/auth");
  }

Upvotes: 2

Views: 5955

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

useFetch is a composable and isn't a direct replacement for fetch function. Composables are supposed to be used in the body of component setup, any other usage needs to be conformed.

useRuntimeConfig should be called in the body of a composable where it's used:

export function useApiFetch<T>(...) {
  const config = useRuntimeConfig();
   return useFetch(config.public.BASE_API_URL + path,
   ..

useFetch should be called once on store creation and the object needs to be reused across the store:

defineStore("auth", () => {
  const logoutFetch = useApiFetch("/logout", { method: "POST", immediate: false });
  ...
  async function logout() {
    await logoutFetch.execute();
    ...

This puts the restriction on the use of auth store, it's limited to the places that are allowed for Nuxt composables:

useFetch is a composable meant to be called directly in a setup function, plugin, or route middleware.

Upvotes: 2

Related Questions