N
Nuxt2y ago
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)
},
})
}
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:
No description
5 Replies
szobi
szobiOP2y ago
ping
harlan
harlan2y ago
to extract the payload you'll either need to use nuxt generate or enable it. Additionally you should use useAsyncData or the useFetch composables as they'll handle the payload extraction (unlike $fetch)
szobi
szobiOP2y ago
i tried use useFetch and results its same, have two request, maybe useFatch has flag to use only on server/client?
harlan
harlan2y ago
But is payload extraction on? It needs the data to hydrate
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server