NuxtN
Nuxt9mo ago
10 replies
Quentin

Custom useFetch and error handling

Hi guys,

I'm using Nuxt 3.16.1 in SSR.

I'm tryin to create a custom useFetch to factorize my API calls, but what I want is : when there's an error during the server rendering, before hydration, throw the error returned by the API using my error.vue file.

Here are my custom useFetch files :
// composables/useApi.js
export function useApi() {
    const nuxtApp = useNuxtApp();

    const setOptions = (options) => {
        options ||= {};

        options.onResponse = ({ response, request }) => {
            if (response.status >= 400) {
                console.log(response.status, request);

                throw createError({
                    statusCode: response.status,
                    statusMessage: request,
                });
            }
        };

        return options;
    };

    const fetch = (url, options) => {
        return useFetch(url, {
            ...setOptions(options),
            $fetch: nuxtApp.$api,
        });
    };

    const get = (url, options) => {
        return nuxtApp.$api(url, {
            ...setOptions(options),
        });
    };

    const post = (url, options) => {
        return nuxtApp.$api(url, {
            ...setOptions(options),
            method: 'POST',
        });
    };

    const put = (url, options) => {
        return nuxtApp.$api(url, {
            ...setOptions(options),
            method: 'PUT',
        });
    };

    return {
        fetch,
        get,
        post,
        put,
    };
}


// plugins/api.js
export default defineNuxtPlugin(() => {
    const api = $fetch.create({
        baseURL: 'http://myapi.com',
        credentials: 'include',
        headers: { accept: 'application/json' },
    });

    return {
        provide: {
            api,
        },
    };
});
Was this page helpful?