1

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


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?

1

2 Answers 2

3

Write a v-if <h1 v-if="movie && movie.length">{{movie[0].id}</h1> So it only renders when data is available.

Sign up to request clarification or add additional context in comments.

1 Comment

This is also the solution, but I can only make one choice :(
1

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: ''
  }
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.