How to fetch and transform data with useAsyncData and Nuxt Content?

683 Views Asked by At

I'm using Nuxt and Nuxt Content in a project, and i want to display the content of a csv file.

According to the documentation, i use the following code:

const { data }  = await useAsyncData<any | Concert[]>('concerts', () => queryContent('/concerts').findOne())

Up to now, I don't encounter any issue. But once i got the data, i need to use it into two functions before displaying it. I tried many things, like using the transform option on the useAsyncData composable, but i didn't manage to make it work, and finally I came up with this solution:

const sorted = computed(() => data.value?.body ? sortConcerts(data.value.body) : null)
const concerts = computed(() => sorted.value ? formatConcerts(sorted.value, en) : null)

This is only working in development if I wrap my content in a component. But when I deploy the application (with "nuxt generate", on netlify), I only see the data the first time I visit the route. The second time, my list is empty.

I feel that I'm not doing the right thing, but I can't find a solution. Does someone have a solution to achieve what i want ?

Thanks a lot!

2

There are 2 best solutions below

1
On

You could try this

<script setup>
  const sorted = ref()
  const concerts = ref()

  const { data }  = await useAsyncData<any | Concert[]>('concerts', () => queryContent('/concerts').findOne())
    
  if (data.value) {
    sorted.value = data.value?.body
    concerts.value = formatConcerts(sorted.value, en)
  }
</script>
1
On

You can try this. Manipulate ALL the variables you need on the server-side (prerender).

<script setup>
const sorted = ref()
const concerts = ref()
            
await useAsyncData("concerts", () => queryContent("/concerts").findOne())
  .then((res) => (sorted.value = sortConcerts(res.value.body)))
  .then(() => (concerts.value = formatConcerts(sorted.value, en)));
</script>