Utilizing Vue3: A guide to constructing an API URL and retrieving data upon route modification

I am currently working on a project where I need to display the borders of a country using the restcountries API. To achieve this, I want to create clickable buttons that will navigate the user to specific border countries.

Here is snippet of my code where I attempt to construct the API URL:

    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)

However, I am facing an issue as the details array is empty when trying to fetch the data. Strangely, refreshing the page resolves the problem and retrieves the data correctly.

Several attempts have been made to resolve this including utilizing beforeMount(), setting a boolean variable for isFetching, fetching the data with an @click-function, and executing these functions within mounted():

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

Below is the structure of my data:

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

Additionally, here is the relevant HTML section responsible for displaying the clickable 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>

Thank you for any assistance you can provide!

Answer №1

It's always good to be patient and wait for responses:

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

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

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

async mounted() {
  await this.fetchBoundaries();
  this.setBoundaries();
  await this.retrieveDetails();
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating HTML content using jQuery by iterating through an array

When I write the following HTML code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <h1 id="message"> </h1> and include the corresponding JavaScript code: messages = ["Here", "are", ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Obtain information from server-side data received from dynamically generated input fields

In my current situation, I have a text input field and a button that, when clicked, adds additional input fields to the page. The JavaScript code I use to achieve this functionality is as follows: var myBtn = document.getElementById('myBtn&apos ...

Handling form submissions in Vue.js before navigating away from the current route

As a newcomer to VueJs, I am facing a problem with creating a form. My goal is to display an alert dialog with the message "you might lose the data, please save the data before you leave," and upon clicking 'yes', the form should be submitted and ...

Guide on sending emails with AngularJS and the Ionic framework

I have been attempting to send an email by using various links, but without success. I am looking for guidance on how to successfully send an email. Below is the code I have been using for sending emails. Any suggestions for changes would be greatly apprec ...

What's the reason behind the console showing an uncaught promise error message?

When attempting to delete some lists from my backend using a fetch request, I encountered an issue. The console is displaying an error message that reads "Uncaught (in promise)." What could be causing this problem? Here is the frontend code snippet for th ...

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Clicking twice in a row on a map

I am encountering an issue while collecting user input from an infowindow. When I click the 'Save' button in the infowindow to save the input, it inadvertently results in moving my marker on the map by clicking somewhere else. All I really want t ...

jquery is failing to load content dynamically

Hi there! I've been working on dynamically loading content, but when clicking on the menu, only the loader appears. I seem to be missing something in the code or doing something wrong. Could you please take a look and let me know? Here's my HTML ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

divide an item according to its category

Hey guys, I need some help with a coding problem! So here's the object I'm working with: var x = {code0: "codefdg", mcode0: "mcodefdg", mcode1: "mcodefdg", comments1: "commentsfdg", code3: "fdg"…} I want to split this object into different pa ...

Troubleshooting Issue with Pull to Refresh and setState in React Native

Implementing Pull to refresh in a React Native App Currently, I am facing an issue with setting the state "refreshing" to true before fetching from the API. This results in a maximum update error being thrown. export default class NotificationScreen ex ...

Validating whether a condition aligns with any element within an array in JavaScript

Is there a better approach to determine if a condition matches any value in an array? For example, if I want to implement retry logic when receiving a 5xx error. var searchUserRequest = httpClient.request(searchUserRequestOptions, (res => { if(r ...

Is it possible to convert an NPM project into a JavaScript file that is compatible with

Can a modestly sized NPM package be transformed into a JavaScript file for direct reference in HTML using a <script> tag? The NPM package in question is straightforward and serves as an API wrapper that I wish to implement without depending on Node. ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Import .vue single file component into PHP application

I've been struggling to integrate a .vue single file component into my php app without using the inline template method. Since I don't have a node main.js file to import Vue and require the components, I'm not sure how to properly register m ...

The "results per page" ajax dropdown in Yii stops working after other ajax content is loaded on the page

One of the views in Yii framework is the "Patients" view, which contains several CGridViews and other elements that are loaded via ajax after the initial view has loaded. Some of these elements are nested within multiple levels of ajax-loaded divs. Within ...

Tips for accessing the data type of a nested property in TypeScript

If I want to keep the following declarations as they are, how can I specifically retrieve the type of the members property? export type Members = { __typename?: 'Members'; id?: Maybe<Scalars['String']>; ... }; export type P ...

What is the best way to toggle the visibility of my menu using JavaScript?

I recently implemented a script to modify a CSS property in my nav bar as I scroll down, triggering the change after reaching 100px. $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if ...

Setting up i18next within an Azure function

In my Azure HTTP trigger function, a client calls with data and the client's culture string, such as "en-US". The index.js file handles the Azure request, while myWorker.js contains a function called doStuff() to prepare data for the client. I am usin ...