The code below should display data fetched from backend upon page load.
Instead, the data shows up only after I make some unrelated change in the code that triggers Vue page update.
Why is it not working upon page load?
<template>
<div>
{{ projects }}
</div>
</template>
<script setup>
import { ref } from 'vue'
let projects = ref([])
const getData = () => {
fetch('https://www.my-site.com/wp/wp-json/projects/v1/posts')
.then(res => res.json()).then((response) => {
projects = response
}).catch((error) => {
console.log(error)
});
}
getData()
</script>
>Solution :
Ah, you are overriding your ref. Assign to its value prop instead:
<script setup>
import { ref } from 'vue'
const projects = ref([]) // <---- use const to make the error impossible
const getData = () => {
fetch('https://www.my-site.com/wp/wp-json/projects/v1/posts')
.then(res => res.json()).then((response) => {
projects.value = response // <---- assign to the ref's value
}).catch((error) => {
console.log(error)
});
}
getData()
</script>