Nuxt asyncData returns empty array for a json5 file with Nuxt Content

507 Views Asked by At

I am using the asyncData method to retrieve the content of a json5 file and I get an empty array.

My file is located at content/myfile.json5

The content is :

[
   {
     id: 1
   },
   {
     id: 21
   }
]

And my method is :

async asyncData({ $content}) {
    const test = await $content('myfile').fetch()

    return {
      test
    }
  }

I am also not able to fetch an array if I use a regular .json file nested in a directory, like /content/places/places.json. The result is an object filled with the first item of my array. It looks like it only works when it's located at the root content folder. I can't find any explanation in the docs.

1

There are 1 best solutions below

2
On

Here is a simple /pages/index.vue file with 2 use cases

<template>
  <pre>{{ nuxtContent }}</pre>
</template>

<script>
export default {
  async asyncData({ $content }) {
    return {
      1️⃣
      // nuxtContent: await $content('testfoobar', { deep: true })
      //   .where({ slug: { $contains: 'yolo' } })
      //   .fetch(),

      2️⃣
      nuxtContent: await $content('testfoobar', 'nice').fetch(),
    }
  },
}
</script>

My project structure enter image description here

nice.json

{
  "name": "bob",
  "age": 25,
  "city": "New York"
}

places.json5

[
  {
    id: 1
  },
  {
    id: 21
  }
]

yolo.json5

[
  {
    id: 777
  },
  {
    id: 999
  }
]

The case 2️⃣ is not working with a .json5 file, not sure if it needs any kind of special syntax or a module to work with it.
Meanwhile, the case 1️⃣ works totally fine with any kind of file (nice.json, places.json5, yolo.json5). And you can also remove the line with the .where to have all of them too.

Here is a screenshot showing 5 objects that I do have in my example (across all the 3 files).

enter image description here

As explained in the documentation here.

PS: if you want to also have hello.md (in the /content directory too), you can use the root path like this: await $content('/', { deep: true }) and you'll get the hello.md + the 5 other nested files.