#NuxtData duplicate items

1 messages · Page 1 of 1 (latest)

lavish boneBOT
#

Hi @native dove. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

This issue appears to be related to how Nuxt handles data caching and payload management with useFetch. The duplicate items in your payload could be caused by several factors:

Possible Causes

  1. Key-related issues: When using useFetch with dynamic keys, Nuxt might not properly deduplicate the data in the payload.

  2. Transform function: Your transform function might be causing issues with how Nuxt handles the data internally. The toSorted method creates a new array, which might be causing unexpected behavior.

  3. Cache management: Nuxt caches data based on keys, and if the key doesn't change but the data does, you might see duplicate entries.

Solutions to Try

  1. Use a more specific key:
    Make sure your key is unique and changes whenever subsheetId.value changes:

    const { data, status } = await useFetch(`/api/scores/${slug}/${subsheetId.value}/team`, {
      key: `team-scores-${slug}-${subsheetId.value}-overall-${Date.now()}`,
      // rest of your code
    })
    

    Adding a timestamp as suggested in this Stack Overflow answer can help prevent caching issues.

  2. Move the transform logic outside of useFetch:
    Try handling the sorting after the data is fetched:

    const { data: rawData, status } = await useFetch(`/api/scores/${slug}/${subsheetId.value}/team`, {
      key: `team-scores-${subsheetId.value}-overall`
    })
    
    const data = computed(() => 
      rawData.value?.toSorted((a, b) => 
        playerIds.indexOf(a.osuUserId) - playerIds.indexOf(b.osuUserId)
      )
    )
    
  3. Clear cache before fetching:
    You could try clearing the Nuxt data cache before fetching:

#
   import { clearNuxtData } from '#app'
   
   // Clear the data before fetching
   clearNuxtData(`team-scores-${subsheetId.value}-overall`)
   
   const { data, status } = await useFetch(...)
  1. Use useAsyncData with explicit control:
    As mentioned in the documentation, useFetch is a wrapper around useAsyncData and $fetch. Using them separately might give you more control:

    const { data, status } = await useAsyncData(
      `team-scores-${subsheetId.value}-overall`,
      () => $fetch(`/api/scores/${slug}/${subsheetId.value}/team`).then(res => 
        res.toSorted((a, b) => playerIds.indexOf(a.osuUserId) - playerIds.indexOf(b.osuUserId))
      )
    )
    

This issue might also be related to a known bug where useFetch runs twice when a page uses a layout, as mentioned in this GitHub issue. If you're using a layout, you might want to try using useLazyFetch instead or provide a static key.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: