Leveraging promises for Axios API calls

I'm currently figuring out the most efficient way to accomplish a task. When I visit a Profile page, the Profile component loads the data for that profile and assigns it to this.profile. Within this data is a file path where I intend to process some data using this file. The approach below seems a bit risky in my opinion.

created() {
    let vm = this;

    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url).then(response => {
        this.profile = response.data;

        d3.json(response.data.fileName)
        .then(function (data) {
            //do some stuff

        }).catch(function (error) {
            // handle error
        });
    });
}

Instead of that, I want to make sure that I have the data from the axios call first. So, I believe I need a promise? I'm thinking more along the lines of:

created() {
    let vm = this;

    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url).then(response => {
        this.profile = response.data;
    }).then() {
        d3.json(response.data.fileName)
        .then(function (data) {
            //do some stuff

        }).catch(function (error) {
            // handle error
        });
    };
}

However, the above code is incorrect but demonstrates what I'm attempting to achieve. I was wondering how I can use deferred and promises to only execute the d3 operation once the axios call has been made.

Thanks

Answer №1

If you want to tackle this issue using promise chaining, assuming that the function d3.json actually returns a promise, follow these steps:

created() {
    let vm = this;
    let url = `/api/profile/${this.$route.params.id}`;
    axios.get(url)
      .then(response => {
        this.profile = response.data
        return d3.json(response.data.fileName)
      }).then(data => {
        //perform necessary actions here
      }).catch(err => {
        //handle error logging
      })
}

Answer №2

Utilizing async/await is a game-changer. Not only does it eliminate the need to store this in a variable, but it also results in cleaner and more understandable code.

async initialize() {

    const url = `/api/data/${this.$route.params.id}`;
    const { info } = await axios.get(url); // Simplified destructuring for better readability
    this.dataInfo = info;

    const chartData = await customLibrary.fetchData(info.fileName);
    //perform desired actions

}

Answer №3

async loadProfileData() {
let instance = this;

let apiEndpoint = `/api/user/${this.$route.params.id}`;
try {
const {userData} = await axios.get(apiEndpoint)

const processedData = await processData(userData.fileName)
    } catch(error) {
      //handle error
    }
}

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

When trying to access the $_SERVER['REQUEST_URI'] in WordPress, the wp_redirect function clears it before I have a chance to read it

My goal is to redirect all traffic on my WordPress site to the homepage if it's not requested by AJAX, while still being able to access the requested path after the redirect. I have managed to set up redirection using wp_redirect in PHP and a template ...

The shared global variable or store feature is currently not functioning as expected in Vue JS

Currently, I am in the process of developing a Simple Web application using Vue JS for educational purposes. Although I am new to Vue JS and still learning the ropes, I have encountered an issue with sharing a state variable across all components. In my a ...

Is it possible to modify state prior to the link being activated in react-router-dom?

I need to gather user information before the link works, but I'm not sure how to do that. The issue is that when I click on the link, the component it's linking to gets activated first without receiving the necessary info. const [userId, setUse ...

The error encountered is due to an invalid assignment on the left-hand side

I'm encountering the error below: Uncaught ReferenceError: Invalid left-hand side in assignment This is the problematic code: if (!oPrismaticMaterial = "") { for (var i = 0; i < oPrismaticMaterial.length; i++) { if (oPrismaticMater ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...

Swapping out the initial icon in a v-list-item with Vuetify

I have a list of items with icons that need to change when clicked. The issue I am facing is that all icons are changing at once because they share the same v-model. How can I modify my code so that only the icon being clicked changes? Here is my current i ...

Navigating with AngularJS to the Public page, such as the signup page

Having an issue with Angular.js (and possibly express) routing. I was able to resolve the routing for regular subpages, but now I need to include some publicly accessible pages like signup, password-lost/reset, and so on. However, whenever I try to access ...

tips on setting the time format in dimple.js

Trying to create a multi-line graph using dimple.js based on some sample code. I have flattened my JSON into an array and thought I had the code down, but I'm stuck. I am including these 2 libraries (using cloudflare dimple for security reasons): &l ...

Include More Items in JSON Encoded List

I am currently using a JSON encoded array to display the users in my database for an auto-suggest feature. Here is an example of how I have implemented it: $sql = "SELECT id, name FROM users"; $result = mysqli_query($conn, $sql); $jsonData = array(); w ...

Learn the process of adding a tag to specific text with the help of JavaScript

I am attempting to implement a feature where the selected text will have a tag added to it. Within a textarea, I have some text entered. The goal is that when I select specific text from the textarea and click a code button, it should insert the tags aro ...

Having trouble with npm and unable to find a solution that works. Any suggestions on how to fix it?

I've been working on a JavaScript project that requires me to import a library, but I keep running into errors with npm every time I try to use it. Here is the error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

How do browsers typically prioritize loading files into the cache?

Out of curiosity, I wonder if the categorization is determined by file names or byte code? It's possible that it varies across different browsers. Thank you! ...

How come my program gets stuck in a never-ending loop whenever I try to access the API?

I am facing an issue while trying to call my API to retrieve the name of a TP. In the view, all I see is [object promise], and in the browser console, it seems like there is an infinite loop happening. HTML: <table [dtOptions]="dtOptions" cla ...

Is it achievable to send information back to a Servlet from JavaScript?

I am currently working on setting up a Servlet that utilizes JDBC for database interactions. My goal is to allow users to log in through a login form and then view the list of available databases in MySQL. I am implementing this functionality dynamically ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

How can I properly initialize React components?

I am currently learning React.js and experimenting with a progress bar animation. I stumbled upon this code that I would like to incorporate into my project, but I am unsure of where to place it. Check out the code here! The JavaScript code in question i ...

What is the best way to choose just one value from an option that includes two variables?

I have a list of properties with numbers and names displayed in my form options. <b-col md="3"> <b-form-group :label="$t('departmentNumber')"> <b-form-select vuelidate v-model="$v.consumptionCon ...

What is the process for uploading a series of images through the fetch API?

I am attempting to use my custom API (Node JavaScript) to upload an array of images. My goal is to save the file names to my database, and the uploading process itself is functioning correctly (the middleware I created for uploading works perfectly as I ha ...

The Meteor method is unable to access the property "quantity" as it is undefined

I encountered an issue with the error message "TypeError: Cannot read property 'quantity' of undefined" while executing a meteor method. Here is the frontend call: Template.listingPage.events({ "submit #add-to-cart": function(e,t){ e.preven ...