Goldsucher
Goldsucher

Reputation: 13

Vue3 - build API url and fetch data after route changed

I am trying to display the borders of a country from restcountries api (https://restcountries.eu/) as clickable buttons.

this is how I try to build the url for the api

    mounted() {

        axios
        .get(this.urlDetail)
        .then(response => (
            this.details = response.data[0]
        ))
        
        this.borders = this.details.borders.join(";");
        this.urlBorders = "https://restcountries.eu/rest/v2/alpha?codes=" + this.borders;


        fetch(this.urlBorders)
            .then(res => res.json())
            .then(data => this.bordersData = data)

the problem is, that the details array is empty at that moment. When I reload the page, the data is fetched correctly.

I tried to:

        document.onreadystatechange = () => {
            if (document.readyState == "complete") {
              console.log('Page completed with image and files!')
            }
        }

this is my data:

    data() {
        return {
            isFetching: true,
            urlDetail: 'https://restcountries.eu/rest/v2/name/' + this.$route.params.countryName,
            details: [],
            borders: "",
            urlBorders: "",
            bordersData: []
        }

this is the relevant html snipped to display the buttons:

<p><strong>Border Countries:</strong><button class="border-button" v-for="border in bordersData"><router-link :to="{ name: 'border', params: {borderName: border.name}}">{{ border.name }}</router-link></button></p>

thanks for helping!

Upvotes: 0

Views: 357

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

Try to wait for responses:

methods: {
  async getBorders() {
    await axios
      .get(this.urlDetail)
      .then((response) => (this.details = response.data[0]));
  },

  setBorders() {
    this.borders = this.details.borders.join(";");
    this.urlBorders =
      "https://restcountries.eu/rest/v2/alpha?codes=" + this.borders;
  },

  async getDets() {
    await axios
      .get(this.urlBorders)
      .then((response) => (this.bordersData = response.data));
    },
  },
},

async mounted() {
  await this.getBorders();
  this.setBorders();
  await this.getDets();
},

Upvotes: 1

Related Questions