Home > front end >  Vue.js : data is visible on console.log but not in DOM
Vue.js : data is visible on console.log but not in DOM

Time:01-01

I using google places-api to get a single or list of places. for each place in the list of places I would like to get an additional data (such as website) - this is done from another api (places details).

The problem is that I can see all the data in google console but not in the DOM - only the data from the the first API is visible ( {{item.website}} property is empty)

here is my code:

<input type="text"  id="searchPlace" v-on:keyup.enter="getPlaces()" placeholder="Type a name, address etc..." v-model="placeToSearch">



 <div v-for="(item, key) in objPlaces" :key="key">
     {{ item.name }} | {{item.place_id}} | {{item.rating}}  | {{item.website}}  
</div>


<script>
var myObject = new Vue({
  el: "#app",
  data: {
    placeToSearch: "",
    objPlaces: null,
  },

methods: {
    getPlaces() {
      let places = null;

      axios
        .get('@Url.Action("GetPlace")', { params: { name: this.placeToSearch }})
        .then((res) => {
          places = res.data.results;
        })
        .finally(() => {
         
          // iterate each place to get its website
          places.forEach(function (el) {
            axios
              .get('@Url.Action("GetPlaceDetails")',{params: { placeId: el.place_id }})
              .then((res) => {
                el["website"] = res.data.result.website;
              });

            this.objPlaces = places;
            console.log(this.objPlaces); // all the data is displayed
          });
        });
    },
  },
  • please note I am using server side to get the details from google api

CodePudding user response:

You're missing the return statement inside data function

CodePudding user response:

You may find it easier to use async/await rather than the callback functions.

const myObject = new Vue({
  el: "#app",
  data() {
    return {
      placeToSearch: "",
      objPlaces: null,
    }
  },
  methods: {
    async getPlaces() {
      const res = await axios.get('@Url.Action("GetPlace")', {
        params: { name: this.placeToSearch },
      });
      const places = res.data.results;

      this.objPlaces = places.map(async (el) => {
        const res = await axios.get('@Url.Action("GetPlaceDetails")', {
          params: { placeId: el.place_id },
        });
        el.website = res.data.results.website;
        return el;
      });
    },
  },
});

Note 1: I haven't tested this, but the general idea is there.

Note 2: Missing try/catch to handle errors from the API.

  • Related