[Vuejs]-Laravel, Vue fetch returns nothing but there is data in console

0👍

  1. Your method doesn’t return anything so there’s nothing to render.
  2. Your method is asynchronous so you could not return any value even if you wanted to.

TL;DR try to avoid using methods in your templates and instead, load data into your data properties. For example

<template>
  <div id="container">
    <span v-if="municipality">{{ municipality }}</span>
    <span v-else>Loading...</span> <!-- 👈 totally optional -->
  </div>
</template>
data () {
  return { municipality: null }
},
methods: {
  loadMunicipality (id) {
    return fetch(`api/biodidb/get_municipality_name_by_id/${id}`)
        .then(res => res.json())
        .then(obj => obj.Municipality)
  }
},
created () {
  this.loadMunicipality(12).then(municipality => {
    this.municipality = municipality
  }).catch(err => {
    console.error(err)
  })
}
👤Phil

Leave a comment