skip to Main Content

This is the code I was using for the authentication front-end, but 2 days ago the following error appeared and I was asking myself how to fix the warning… but I couldn’t figure it out how to solve it.

Warning:

[nuxt] [useFetch] Component is already mounted, please use $fetch instead. See https://nuxt.com/docs/getting-started/data-fetching**

My Code :

import type { UseFetchOptions } from "nuxt/app";
 
import { useRequestHeaders } from "nuxt/app";
 
export function useApiFetch<T>(path: string, options: UseFetchOptions<T> = {}) {
    let headers: any = {
        accept: "application/json",
        referer: "http://localhost:3000",
    };
 
    const token = useCookie("XSRF-TOKEN");
 
    if (token.value) {
        headers["X-XSRF-TOKEN"] = token.value as string;
    }
 
    if (process.server) {
        headers = {
            ...headers,
 
            ...useRequestHeaders(["cookie"]),
        };
    }
 
    return useFetch("http://localhost:8000" + path, {
        credentials: "include",
 
        watch: false,
 
        ...options,
 
        headers: {
            ...headers,
 
            ...options?.headers,
        },
    });
}

I tried to disable TypeScript and eventually I tried to implement $fetch but in the return object I have have many errors.

2

Answers


  1. <script setup lang="ts">
    import { useApiFetch } from '~/file'
    const { data, error, execute } = useApiFetch(
      '/api/path', 
      { immediate: false }
    )
    const doFetch = async () => {
      await execute()
    }
    </script>
    

    see this: https://www.youtube.com/watch?v=njsGVmcWviY&ab_channel=AlexanderLichter

    Login or Signup to reply.
  2. Use fetch. Modify your code to this:

    import { useRequestHeaders } from "nuxt/app"
    
    export async function useApi(path, options) {
        const config = useRuntimeConfig()
    
        let headers = {
            accept: "application/json",
            referer: config.public.appUrl
        }
    
        const token = useCookie('XSRF-TOKEN');
    
        if (token.value) {
            headers['X-XSRF-TOKEN'] = token.value;
        }
    
        if (process.server) {
            headers = {
                ...headers,
                ...useRequestHeaders(["cookie"]),
            }
    
        }
    
        let data, error
    
        try {
            data = await $fetch(config.public.apiUrl + path, {
                credentials: "include",
                watch: false,
                ...options,
                headers: {
                    ...headers,
                    ...options?.headers
                }
            })
        }
        catch (e) {
            error = e
        }
        return { data: ref(data), error: ref(error) }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search