how do I get one quote to show instead of all API in vue3 script setup?

js and Im using composition API with script setup. Im doing a simple quote generator and fetching API. Its just that I get ALL quotes to show when I press the button. How can I do so only one random quote shows at the time?

<template>
  <div class="about">
  <div>
    <h1 class="mb-6">This is a random Blog page</h1>
  </div>
  <div v-for="quote in listItems" class="justify-center flex flex-column text-center">
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" class="bg-orange-500">Get a new blog</button>
  </div>

</template>

<script setup>
import {ref} from 'vue'
let id = ref(0)
let title = ref('hallo')
let body = ref('random blogs')
const listItems = ref([])

async function getData(){
  const api = await fetch('https://jsonplaceholder.typicode.com/posts')
  const finalApi = await api.json()
  listItems.value = finalApi
  const index = Math.floor(Math.random()*api.length)
  const quoteOfTheDay = finalApi.value[index]
  quoteOfTheDay.value = quoteOfTheDay.body
 
  
}
</script>

>Solution :

You’re looping through all the api responses in your template. Instead just display one.

<template>
  <div class="about">
  <div>
    <h1 class="mb-6">This is a random Blog page</h1>
  </div>
  <div v-if="quote" class="justify-center flex flex-column text-center">
    <h5> ID: {{ quote.id }}</h5>
    <h2> Title: {{ quote.title }}</h2>
    <h3> Body: {{ quote.body }}</h3>
  </div>
  <button @click="getData()" class="bg-orange-500">Get a new blog</button>
  </div>

</template>

<script setup>
import {ref} from 'vue'
let id = ref(0)
let title = ref('hallo')
let body = ref('random blogs')
const listItems = ref([])

let quote = ref(null)

async function getData(){
  const api = await fetch('https://jsonplaceholder.typicode.com/posts')
  const finalApi = await api.json()
  const index = Math.floor(Math.random() * finalApi.length)
  quote.value = finalApi[index]
  
}
</script>

Leave a Reply