alexandraleigh
alexandraleigh

Reputation: 187

VueJS data from nested Axios requests not rendering in view

I am trying to list a set of posts from an API on a page using VueJS and Axios. The issue I am facing is one piece of the data (the post url) needs to be retrieved with a separate API call for that specific post and they provide the url for that data in the initial API call. I have the first part working perfectly, but I can't get the href to render in the view when the value is showing up in the Vue devtools.

JS

const vm = new Vue({
  el: '#app',
  data: {
    posts: []
  },
  mounted() {
    this.getPosts();
  },
  methods: {
    getPosts() {
      axios.get("api_url")
      .then((response) => {
        this.posts = response.data.posts;
        // Get URL for each post from separate API call
        this.posts.map(post => {
          axios.get(post.details_url+"&output=json")
          .then((response) => {
            post.official_url = response.data.post.pet_details_url;
          }).catch( error => { console.log(error); });
        });
      }).catch( error => { console.log(error); });
    }
  }
});

HTML

<div id="app">    
  <div v-for="post in posts">
    <a :href="post.official_url"> //href won't render
      <h2>{{ post.title }}</h2>
      <p>{{ post.text }}</p>
    </a>
  </div>
</div>

Data showing up in Vue DevTools

Upvotes: 1

Views: 2403

Answers (1)

ittus
ittus

Reputation: 22393

It might be reactive problem. You can try Vue.set

getPosts() {
    let vm = this
    axios.get("api_url")
    .then((response) => {
      this.posts = response.data.posts;
      // Get URL for each post from separate API call
      
      this.posts.map((post, index) => {
        axios.get(post.details_url+"&output=json")
        .then((response) => {
          post.official_url = response.data.post.pet_details_url;
          Vue.set(vm.posts, index, JSON.parse(JSON.stringify(post)))
        }).catch( error => { console.log(error); });
      });
    }).catch( error => { console.log(error); });
  }

Upvotes: 4

Related Questions