Vue.js Multiple API Call with relation

Viewed 1229

I have this structure folder:

components/
  character.vue
pages/
  teams/
    _id.vue

In the _id.vue file I have a mounted function to get the team with a specific ID:

data () {
  return{
    id: this.$route.params.id,
    team: [],
  }
},
mounted () {
  axios.get(`https://example.com/admin/wp-json/wp/v2/teams/${this.id}`)
    .then(response => {
      this.team = response.data
  }),
}

Here in this stage I have the team object.

What I want to do is to bring one more object who has related with team object in this page and carry to character component.


I want to call this URL https://example.com/admin/wp-json/wp/v2/character/{character_id} and get the specific character object who belong to the team.

The character ID is in the team.acf.acf_choose_character.

I believe that what I am asking for has been understood.

Thanks in advance!

Below is the team object:

"acf": {
  "acf_choose_character": [
    11
  ],
  "acf_choose pathways": [
    159,
    166,
    167
  ],
  "acf_team_final_score": ""
},
1 Answers

You can make a second axios call in the callback of the first one.

mounted () {
  axios.get(`https://example.com/admin/wp-json/wp/v2/teams/${this.id}`)
    .then(response => {
      this.team = response.data
      axios.get(`https://example.com/admin/wp-json/wp/v2/character/${this.team.acf.acf_choose_character[0]}`)
        .then(response2 => {
          this.character = response2.data
      }),
  }),
}

If you want to escape the callback hell, you can use ES6 async/await

async mounted () {
  const response = await axios.get(`https://example.com/admin/wp-json/wp/v2/teams/${this.id}`)
  this.team = response.data

  const response2 = await axios.get(`https://example.com/admin/wp-json/wp/v2/character/${this.team.acf.acf_choose_character[0]}`)
  this.character = response2.data
}
Related