N
Nuxt2mo ago
Uzyxen

useFetch server-side

how to send api request via useFetch only server-side?
5 Replies
kapa.ai
kapa.ai2mo ago
Hi @Uzyxen. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To send an API request using useFetch only on the server-side in Nuxt, you can utilize the server option of useFetch. Here's how you can do it:
const { data } = await useFetch('/api/endpoint', {
server: true,
lazy: false
})
const { data } = await useFetch('/api/endpoint', {
server: true,
lazy: false
})
By setting server: true, you ensure that the fetch request is only executed on the server-side. The lazy: false option ensures that the request is made immediately during server-side rendering. It's important to note that useFetch is designed to work isomorphically (both on server and client), but this configuration restricts it to server-side only. This approach is useful when you want to fetch data only during server-side rendering and not on the client-side. Remember that useFetch is a composable meant to be called directly in a setup function, plugin, or route middleware. It handles adding responses to the Nuxt payload, allowing data to be passed from server to client without re-fetching on the client side during hydration Docs > Api > Composables > useFetch (https://nuxt.com/docs/api/composables/use-fetch). If you need more control over headers or cookies in your server-side request, you can use useRequestHeaders to access and proxy headers to the API from the server-side Docs > Getting-started > Data fetching > Passing Headers and cookies (https://nuxt.com/docs/getting-started/data-fetching#passing-headers-and-cookies). ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@361925793397473281> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Uzyxen
UzyxenOP2mo ago
I'm getting an error "hydration text content mismatch on". I have to send useFetch requests in a loop and add responses to the array. For a while it's good and array has few different elements but after 1-2 seconds it's the same code:
const { data: images } = await useFetch(`http://localhost:5271/api/image/uploadGalleryImages/${id}`, {
responseType: 'json',
method: 'get',
headers: {
'Content-Type': 'application/json',
}
});

const files = ref([]);
const formData = new FormData();
const imageSrc = ref(null); // Ustawienie na null na początku

for (const image of images.value) {
const { data: singleImage } = await useFetch('http://localhost:5271/api/image/uploadGallerySingleImage', {
responseType: 'arrayBuffer',
method: 'post',
body: JSON.stringify({
ImagePath: image.imageSource
}),
headers: {
'Content-Type': 'application/json',
},
server: true,
lazy: false
});

console.log(singleImage);

//console.log(singleImage);

const mimeType = "image/png";
const blob = new Blob([singleImage.value], { type: mimeType });
const file = new File([blob], image.imageSource.split('/').pop(), { type: mimeType });

//console.log(file);

//console.log(singleImage);
files.value.push(file);
}
const { data: images } = await useFetch(`http://localhost:5271/api/image/uploadGalleryImages/${id}`, {
responseType: 'json',
method: 'get',
headers: {
'Content-Type': 'application/json',
}
});

const files = ref([]);
const formData = new FormData();
const imageSrc = ref(null); // Ustawienie na null na początku

for (const image of images.value) {
const { data: singleImage } = await useFetch('http://localhost:5271/api/image/uploadGallerySingleImage', {
responseType: 'arrayBuffer',
method: 'post',
body: JSON.stringify({
ImagePath: image.imageSource
}),
headers: {
'Content-Type': 'application/json',
},
server: true,
lazy: false
});

console.log(singleImage);

//console.log(singleImage);

const mimeType = "image/png";
const blob = new Blob([singleImage.value], { type: mimeType });
const file = new File([blob], image.imageSource.split('/').pop(), { type: mimeType });

//console.log(file);

//console.log(singleImage);
files.value.push(file);
}
@kapa.ai
kapa.ai
kapa.ai2mo ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- The hydration mismatch error you're experiencing is likely due to the asynchronous nature of your code and how it interacts with server-side rendering and client-side hydration in Nuxt. Let's break down the issue and suggest some solutions: 1. Hydration Mismatch: The error "hydration text content mismatch" occurs when the content rendered on the server doesn't match what's rendered on the client during hydration. This is a common issue when dealing with asynchronous operations that may complete at different times on the server and client YouTube: Nuxt 3: The new Vue 3.4 feature NOBODY talks about… (https://www.youtube.com/watch?v=d4-OjlicbiY). 2. Using useFetch in a loop: Using useFetch inside a loop can be problematic, especially when it's used to populate an array. The server might complete these requests faster or slower than the client, leading to mismatches. 3. Server-only fetching: You're using server: true and lazy: false in your useFetch call, which means these requests are only happening on the server. This can lead to issues if you're trying to use this data on the client side. To address these issues, consider the following approaches: 1. Use useAsyncData for multiple requests: Instead of using useFetch in a loop, you can use useAsyncData to handle all your requests in one go:
const { data: processedImages } = await useAsyncData('processedImages', async () => {
const { data: images } = await $fetch(`<http://localhost:5271/api/image/uploadGalleryImages/${id}`>);

const processedFiles = await Promise.all(images.map(async (image) => {
const singleImage = await $fetch('<http://localhost:5271/api/image/uploadGallerySingleImage',> {
method: 'POST',
body: { ImagePath: image.imageSource },
});

const mimeType = "image/png";
const blob = new Blob([singleImage], { type: mimeType });
return new File([blob], image.imageSource.split('/').pop(), { type: mimeType });
}));

return processedFiles;
});

const files = ref(processedImages.value || []);

const { data: processedImages } = await useAsyncData('processedImages', async () => {
const { data: images } = await $fetch(`<http://localhost:5271/api/image/uploadGalleryImages/${id}`>);

const processedFiles = await Promise.all(images.map(async (image) => {
const singleImage = await $fetch('<http://localhost:5271/api/image/uploadGallerySingleImage',> {
method: 'POST',
body: { ImagePath: image.imageSource },
});

const mimeType = "image/png";
const blob = new Blob([singleImage], { type: mimeType });
return new File([blob], image.imageSource.split('/').pop(), { type: mimeType });
}));

return processedFiles;
});

const files = ref(processedImages.value || []);

This approach ensures that all asynchronous operations are completed before the data is returned, reducing the chance of hydration mismatches Docs > Getting-started > Data fetching > The need for useFetch and useAsyncData (https://nuxt.com/docs/getting-started/data-fetching#the-need-for-usefetch-and-useasyncdata). 2. Use client-only component: If the image processing is not critical for SEO or initial render, you can wrap this logic in a client-only component to avoid server-side rendering altogether:
<client-only>
<ImageProcessor :id="id" />
</client-only>

<client-only>
<ImageProcessor :id="id" />
</client-only>

This ensures that the processing only happens on the client side, eliminating hydration mismatches. 3. Use isHydrating check: You can use nuxtApp.isHydrating to check if the app is currently hydrating and avoid running certain code during this phase Docs > Api > Composables > useNuxtApp > Properties > isHydrating (https://nuxt.com/docs/api/composables/use-nuxt-app#ishydrating):
const nuxtApp = useNuxtApp();
if (!nuxtApp.isHydrating) {
// Your image processing logic here
}

const nuxtApp = useNuxtApp();
if (!nuxtApp.isHydrating) {
// Your image processing logic here
}

Remember, hydration mismatches often occur when the state changes between server-side rendering and client-side hydration. By ensuring that your asynchronous operations are completed before rendering or by moving them entirely to the client side, you can avoid these issues. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai2mo ago
<@361925793397473281> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server