Issues when displaying values in template

I’m retrieving and displaying values successfully in my template from an API, it’s an array inside another array.

setup(){

const vf=ref(“”);

getData.data(“/home”).then(function(r: any){
console.log(r.data);
vf.value=r.data;
});

}

In the template, I display like this:

{{vf[0].name}}

It works the first time, when the page is reload again, however, I get this error in the console:

Uncaught (in promise) TypeError: Cannot read property ‘name’ of undefined

What am I doing wrong? I tried using v-for, it worked but I would like to get just one value from that array.

I tried using

data(){
return{
info: [ ]
}
}

But I can’t get it working. If I’m not mistaken, that should be the best way to assign a value retrieved from the promise to a variable, thus to be rendered in the template, but it gives me an error: “cannot use this… …it has to be type any”, but when I set it to type any, it gives me another error, so I ended up giving up and using ref instead.

Is there any way to solve this problem?

Thank you in advance.

I am not quite sure how ref() works but it looks like you are assigning r.data to vf.value but looking for name in vf[0]. Should it be {{ vf.value[0].name ?

I’ve had problems updating variables declared in setup() so I’d change it to this

  data() {
    return {
      vf: []
    }
  },
  ionViewDidEnter() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      getData.data("/home").then(function(r: any){
        console.log(r.data);
        vf = r.data;
      });
    }
  }
1 Like

Thank you but the “value” is just to assign a value to a constant. It’s weird because it actually works but then, when I refresh the page, it no longer works.

UPDATE

I solved the problem by assign a const for each array.

setup(){

const vf=ref("");
const name=ref("");

getData.data("/home").then(function(r: any){

   vf.value=r.data;
   name.value=r.value[0].name;
});

}