Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading