Hi everyone!
I’m having trouble using the <script setup>
syntax when it comes to loading data from an async API call. I think I’m missing some fundamental understanding. I know that, despite reading the docs, and using other resources, I don’t quite understand the reactivity system.
Here is my component:
<template>
<h1>{{eventdetails.title}}</h1> <!-- eventdetails.title never gets updated here. This is the problem. -->
</template>
<script setup lang="ts">
import {getEvent} from "../services/EventService";
import {reactive} from 'vue'
import {HEvent} from "../types";
let eventdetails = reactive({} as HEvent)
getEvent(1) // A helper function that uses axios to make an API call, returns a Promise. Here I'm passing a hardcoded '1' to get the event with id 1
.then(response => {
eventdetails = response.data
console.log(eventdetails) //shows that eventdetails has been correctly updated
})
.catch(error => {
console.log(error)
})
</script>
The problem is that in the template {{eventdetails.title}}
never gets updated with the data from the call.
I’ve tried initializing the eventdetails
variable in other ways:
let eventdetails = reactive({})
let eventdetails = ref({})
let eventdetails = {}
I have also tried placing the getEvent()
call within an onMounted
hook (although I don’t think that should be necessary), but it didn’t work.
What am I doing wrong?