Search code examples
apivue.jsresponse

VueJS - How to use the response of one API call in another API call in the same component


Here is my scenario, i am trying to use the id coming from one API response in another API :

Below is Component.vue:

<template>
  <div class="Contents">
      <div class="vx-col" v-for="idea in ideas" v-bind:key="idea.id">
          <vx-card>
            ...
            <div>
              {{idea.name}} of {{idea.id}}
            </div>
            <div v-if="sum">
              {{sum.total}}
            </div>
            ...
          </vx-card>
     </div>
  </div>
</template>

<script>
...

async created () {

  await this.$http.get('/ideas')
    .then((response) => { this.ideas = response.data })
    .catch((error) => { console.log(error) })
},
methods: {

  getSumOfIdeas(id){
    this.$http.get('/sum_of_ideas/'+ id +'/everything')
      .then((response) => { this.sum = response.data })
      .catch((error) => {console.log(error)})
  }
},
mounted (){
  this.getSumOfIdeas(this.ideas.id)   //Here i am trying to give that id coming from the /ideas 
}
</script>

Here is what console.log(response.data) gives in /ideas:

enter image description here

Don't know where i am going wrong, currently in my console i get an error as :

 /sum_of_ideas/undefined/everything // so here id coming from the /ideas should have been rendered.

To make it clear i have used an example of {{idea.id}} and this displays just the number each time it loops.

Please help me in this, i want to use the response coming from the /ideas ie id in another response here it is /sum-of-ideas.


Solution

  • When you are calling this.getSumOfIdeas(this.ideas.id) you are trying to access id of ideas which does not exist. Either use something like this.getSumOfIdeas(this.ideas[0].id) to access id of the first object or use a loop to iterate over the ideas and call this.getSumOfIdeas(this.ideas.id).

    this.ideas.forEach(idea => this.getSumOfIdeas(idea.id))