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

Can't fetch data on page load with Vue 3

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?

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

<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> 
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