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 to display object in a variable in Vue 3 script setup

I can’t display object in Vue 3 script setup. I used ref, reactive and standard variables but all scenarios is unsuccessful.

I want to reflect the response from the getDetail request to the screen. getDetail is fetching this data asynchronously. I run into a problem in every scenario.

ref() usage


<script setup>
let movie = ref([])

const getMovieData = async ()=> {

try {
const data =  await getDetail('movie', route.params.id)
movie.value.push(data)
}
catch (e){
console.log(e)
}

}
getMovieData()
</script>
<template>

<h1>{{movie[0].original_title}}</h1>

</template>

I am able to show data in this usage but I am getting these errors
ref() Error

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


reactive() usage


<script setup>
let movie = reactive({
  data:null
})

const getMovieData = async ()=>{
  try {
    const data =  await getDetail('movie', route.params.id)
    movie.data = data
  }catch (e){
    console.log(e)
  }
}
getMovieData()
</script>

<template>
<h1>{{movie.data.original_title}}</h1>
</template>

In this usage I can show data but I get similar errors
reactive()errors


Standart variable usage

<script setup>

let movie

const getMovieData = async ()=>{
  try {
    const data =  await getDetail('movie', route.params.id)
    movie =data
  }catch (e){
    console.log(e)
  }
}
getMovieData()
</script>

<template>
<h1>{{movie.id}}</h1>
</template>

In this usage, the data does not appear on the screen, because the movie object is formed asynchronously.


How do I manage to display this object on the screen in the most correct way without getting an error?

>Solution :

Template code runs immediately on component creation. In each case, before movie has been asynchronously assigned, your template code is trying to access some non-existent property. optional chaining is arguably the easiest way to prevent these types of errors:

movie[0]?.original_title

Another option is to provide a default value that matches your template usage so it doesn’t error out:

let movie = ref([
  {
    original_title: ''
  }
])
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