NuxtN
Nuxt14mo ago
Ulrich

Reactivity with UseFetch

Hi i have a custom useFetch composable for fetching my data from an external API. In /location page, when the user arrive, a first fetch is made with filterOptions (a reactive object that can have empty string at start), this page has a Filter component that content filters of the page and update filterOptions object according to user preferences.
I want to remove empty key in filterOptions when the request is been made without loosing reactivity(refetch when some of filterOptions change).
I stuck on it. That's my files.

// composables/use-api.ts
import type {UseFetchOptions} from "nuxt/app";
export function useApi<T>(
    url: string | (() => string),
    options?: UseFetchOptions<T>,
) {
    return useFetch(url,{
        ...options,
        $fetch: useNuxtApp().$api as typeof $fetch,
    })
}


// plugins/api.ts
export default defineNuxtPlugin((nuxtApp) => {
    const { token } = useAuth()
    const runtimeConfig = useRuntimeConfig()
    const api = $fetch.create({
        baseURL: runtimeConfig.public.apiBaseUrl,
        onRequest({ request, options, error }) {
            if (token.value) {
                const headers = options.headers ||= {}
                if (Array.isArray(headers)) {
                    headers.push(['Authorization', `${token.value}`])
                } else if (headers instanceof Headers) {
                    headers.set('Authorization', `${token.value}`)
                } else {
                    headers.Authorization = `${token.value}`
                }
            }
        },
        async onResponseError({ response }) {
            if (response.status === 401) {
                await nuxtApp.runWithContext(() => navigateTo('/login'))
            }
        }
    })
    // Expose to useNuxtApp().$api
    return {
        provide: {
            api
        }
    }
})


Thanks
Was this page helpful?