N
Nuxt4d ago
Cordobes

in development comments are fetching correctly, on production theres no fetch

const fetchComments = async () => { try { const { data } = await useAsyncData( 'comments', () => $fetch('/api/v1/comments', { method: 'GET', params: { sitekey, post_id: postId, hostname: referer } }) ) console.log(data) const commentsArray = Array.isArray(data) ? data : (data as { comments: Comment[] })?.comments || [] comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) } catch (error) { console.error('Error fetching comments:', error) comments.value = [] } } fetchComments()
5 Replies
kapa.ai
kapa.ai4d ago
Hi @Cordobes. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- Based on your code, I can see you're experiencing an issue where comments are fetching correctly in development but not in production. This is likely related to how data fetching works in Nuxt 3 across different environments. Possible Issues 1. Server vs Client Rendering: In production, your code might be executing in a different environment than in development, causing the fetch to behave differently. 2. Missing Key Parameter: Your useAsyncData call might be generating different keys between environments. 3. Hydration Issues: There could be a hydration mismatch between server and client. Recommended Solutions 1. Add a Custom Key Recent Nuxt issues show that useFetch and useAsyncData can have hydration problems in production. Adding a custom key can help:
const fetchComments = async () => {
try {
const { data } = await useAsyncData(
`comments-${postId}-${sitekey}`, // Add a more specific key
() => $fetch('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
})
)
console.log(data.value) // Access .value since data is a ref
const commentsArray = Array.isArray(data.value) ? data.value : (data.value as { comments: Comment[] })?.comments || []
comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
} catch (error) {
console.error('Error fetching comments:', error)
comments.value = []
}
}
const fetchComments = async () => {
try {
const { data } = await useAsyncData(
`comments-${postId}-${sitekey}`, // Add a more specific key
() => $fetch('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
})
)
console.log(data.value) // Access .value since data is a ref
const commentsArray = Array.isArray(data.value) ? data.value : (data.value as { comments: Comment[] })?.comments || []
comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())
} catch (error) {
console.error('Error fetching comments:', error)
comments.value = []
}
}
2. Use console.log for Debugging Add more console logs to see what's happening in production:
console.log('Fetching comments with params:', { sitekey, postId, referer })
const { data, error } = await useAsyncData(...)
console.log('Fetch result:', data.value, 'Error:', error.value)
console.log('Fetching comments with params:', { sitekey, postId, referer })
const { data, error } = await useAsyncData(...)
console.log('Fetch result:', data.value, 'Error:', error.value)
3. Consider Using $fetch with useAsyncData Instead Some users have reported that switching from useFetch to useAsyncData with $fetch resolves production issues:
const fetchComments = async () => {
try {
const { data } = await useAsyncData(
`comments-${postId}`,
() => $fetch('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
})
)
// Rest of your code
} catch (error) {
console.error('Error fetching comments:', error)
comments.value = []
}
}
const fetchComments = async () => {
try {
const { data } = await useAsyncData(
`comments-${postId}`,
() => $fetch('/api/v1/comments', {
method: 'GET',
params: {
sitekey,
post_id: postId,
hostname: referer
}
})
)
// Rest of your code
} catch (error) {
console.error('Error fetching comments:', error)
comments.value = []
}
}
4. Check Server Configuration Make sure your API endpoint is properly accessible in production. The issue might be related to your server configuration rather than the Nuxt code. 5. Access Data Value Correctly Remember that data from useAsyncData is a ref, so you need to use data.value to access its content:
console.log(data.value)
const commentsArray = Array.isArray(data.value) ? data.value : (data.value as { comments: Comment[] })?.comments || []
console.log(data.value)
const commentsArray = Array.isArray(data.value) ? data.value : (data.value as { comments: Comment[] })?.comments || []
This issue appears similar to a known problem discussed in a GitHub issue where useFetch and useAsyncData can have hydration failures in production builds. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Cordobes
CordobesOP4d ago
@kapa.ai const fetchComments = async () => { try { const { data } = await useAsyncData( comments-${postId}-${sitekey}, // Add a more specific key () => $fetch('/api/v1/comments', { method: 'GET', params: { sitekey, post_id: postId, hostname: referer } }) ) console.log(data.value) // Access .value since data is a ref const commentsArray = Array.isArray(data.value) ? data.value : (data.value as { comments: Comment[] })?.comments || [] comments.value = commentsArray.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()) } catch (error) { console.error('Error fetching comments:', error) comments.value = [] } } fetchComments()
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- I see you've implemented the changes I suggested in your fetchComments function. Let me analyze your updated code and provide additional insights. Your implementation looks good with the specific key for useAsyncData and proper access to data.value. However, there are a few additional considerations for ensuring this works correctly in production: Potential Issues to Check 1. Server-Only Middleware: If this code is running in a server-only middleware, there might be issues with refreshing the data on the client side. According to a GitHub issue, when data is defined in server-only middleware, the client can't refresh it using the key because it wasn't initialized on the client side. As mentioned in this GitHub issue, "Since useAsyncData('profile', ....) was not initialized on the client side, Nuxt is unable to find the corresponding logic to refetch the data." 2. Hydration Mismatch: Recent versions of Nuxt (especially 3.16+) have had issues with hydration mismatches between server and client when using data fetching composables. Additional Recommendations 1. Ensure Consistent Environment: Make sure your API endpoint is accessible in both development and production environments. 2. Consider Using refreshNuxtData: If you need to refresh the data later:
// To refresh the data later
await refreshNuxtData(`comments-${postId}-${sitekey}`)

// To refresh the data later
await refreshNuxtData(`comments-${postId}-${sitekey}`)

This utility is documented in the refreshNuxtData API. 3. Debug Production Issues: Enable debugging in your Nuxt config to get more insights:
// nuxt.config.js
export default defineNuxtConfig({
debug: true,
// other config
})

// nuxt.config.js
export default defineNuxtConfig({
debug: true,
// other config
})

4. Check for Immediate Execution: If you're calling fetchComments() directly in your component setup, it will run immediately. If you want to delay execution, consider using the immediate: false option:
const { data, execute } = await useAsyncData(
`comments-${postId}-${sitekey}`,
() => $fetch('/api/v1/comments', {
// your params
}),
{ immediate: false }
)

// Then call execute() when needed
execute()

const { data, execute } = await useAsyncData(
`comments-${postId}-${sitekey}`,
() => $fetch('/api/v1/comments', {
// your params
}),
{ immediate: false }
)

// Then call execute() when needed
execute()

5. Access Cached Data: If you need to access the data elsewhere, you can use useNuxtData:
const { data: cachedComments } = useNuxtData(`comments-${postId}-${sitekey}`)

const { data: cachedComments } = useNuxtData(`comments-${postId}-${sitekey}`)

Your implementation with the specific key should help resolve the issue where data wasn't being fetched in production. If you're still experiencing problems, consider checking the network requests in your browser's developer tools to see if the API call is being made and what response it's receiving. Let me know if you encounter any specific errors after implementing these changes. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1275808916168511508> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?