NuxtN
Nuxt4y ago
5 replies
szobi

double request after use $fetch

I have written a wrapper for get data from the api, the problem occurs on the SSR side because when entering the website for the first time, queries that should be sent via SSR are also sent via the client. The differences can be seen when I add new Date() in console.log. anyone had such a problem?
its wrapper:

export const useApi = async <T = unknown>(
    endpoint: string,
    opts?: UseApiRequestOptions,
): Promise<T> => {
    const {
        public: { BACKEND_API_URL },
    } = useRuntimeConfig()
    const {
        $state: { token },
    } = useUserStore()
    const baseURL = BACKEND_API_URL
    const headers: { Accept: string; Authorization?: string } = {
        Accept: 'application/json',
    }

    if (token) {
        headers.Authorization = `Bearer ${token}`
    }
    const { $humps } = useNuxtApp()
    let body = opts?.body
    const query = opts?.query
    if ($humps) {
        body = $humps.decamelizeKeys(body)
    }

    return await $fetch(endpoint, {
        method: opts?.method,
        body,
        query,
        baseURL,
        headers,
        params: opts?.params,
        onResponse({ request, response }) {
            if ($humps) {
                response._data = $humps.camelizeKeys(response._data)
            }
            return Promise.resolve()
        },
        onResponseError({ request, response }): Promise<any> {
            return Promise.reject(response)
        },
    })
}


times:
image.png
Was this page helpful?