Home > Software design >  fetch data in nuxt3 not rendering in templete
fetch data in nuxt3 not rendering in templete

Time:01-15

I am trying to set api in nuxt 3 using this code:

<template>

    <div>
        <pre>{{ $data }}</pre>
        <ul>
            <li v-for="planet in planets" :key="planet.slug">
                <NuxtLink :to="planet.slug">
                    {{ planet.title }}
                </NuxtLink>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    async fetch() {
        this.planets = await fetch('https://api.nuxtjs.dev/planets').then(res => 
        res.json()

        )
    },
    data() {
        return {
            planets: [],
        } 
    },
}
</script>

but I only got this result in browser!!

"planets": []

I trid to use usefetch and useAsyncData but couldnot success could anyone help me to know my mistake!

CodePudding user response:

Here is how to perform data fetching using the Option API : https://nuxt.com/docs/getting-started/data-fetching#options-api-support

So in your case, this is how you should fetch your data.

<template>
  <div>
    <pre>{{ $data }}</pre>
    <ul>
      <li v-for="planet in planets" :key="planet.slug">
        <NuxtLink :to="planet.slug">
          {{ planet.title }}
        </NuxtLink>
      </li>
    </ul>
  </div>
</template>

<script>
export default defineNuxtComponent({
  fetchKey: 'hello',
  async asyncData() {
    return {
      planets: await $fetch('https://api.nuxtjs.dev/planets'),
    };
  },
});
</script>

Please, note that, as the doc says, using <script setup lang="ts"> is the recommended way of declaring Vue components in Nuxt 3.

You can find more information about it here: https://nuxt.com/docs/api/utils/define-nuxt-component

CodePudding user response:

Thanks for BghinC.

Now I face this: data rendered as json only

<script setup>
const { data: users } = await useFetch('/api/users', { key: 'users' })
</script>   

<template>

    <div>
        {{ users }}
 
    </div>
</template>

but when I request data inside < li > not coming!

       <ul>
            <li v-for=" user in users" :key="user.id">
                {{ user.name }}
            </li>
        </ul>

How can I render it inside html elements?

  • Related