Proceed with the second axios call only if the first one meets certain conditions

I am attempting to implement a feature where I can check the response object from the initial axios call, and if it is empty, proceed to the second call (otherwise, I will generate an error message).

Essentially, the second axios call should only be triggered if the userStatus object is empty. While both axios calls function independently, how can I ensure that the second call is made when the object is empty?

Currently, I receive a 200 response from the first axios call and an empty userStatus object in the console, but the second call does not occur.

changeStatus: function(event) {

  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
  .then((response) => {
      this.userStatus = response.data
  })

  if(this.userStatus.length < 1){

    let data = {
        id: event.id,
        status: 'A'
    };

    axios.post('/status/change',data)
    .then((response) => {
        if (response.data.success == false) {
            this.errors = [];
            const errorLog = Object.entries(response.data.errors);
            for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
            }
        }
    })


  }else{
    console.dir('No');
  }
},

Answer №1

One issue that may arise is due to the difference in the execution process of your code and Axios calls. Your code runs synchronously, one line after the other, while Axios calls are asynchronous. This means that while your first Axios call is still processing in the background, the check

if(this.userStatus.length < 1)
is being evaluated before the first call is completed.

If your second Axios call relies on the result of the first one, you should place the second call inside the .then() handler of the first call like this:

changeStatus: function(event) {
  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
    .then((response) => {
      this.userStatus = response.data;

      if(this.userStatus.length < 1) {
        let data = {
          id: event.id,
          status: 'A'
        };

        axios.post('/status/change',data)
          .then((response) => {
            if (response.data.success == false) {
              this.errors = [];
              const errorLog = Object.entries(response.data.errors);

              for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
              }
            }
          });
       } else {
         console.dir('No');
       }
    });
},

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

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Exploring the world of web scraping using NodeJS and cheerIO

Can anyone help me figure out why I can't retrieve the HTML content while web scraping with Node.js and Cheerio? When I use the .html() function, it's showing an error saying that it is not a function. Here is the code snippet where I'm try ...

Unable to import library in Angular framework

I'm currently in the process of setting up js-beautify, which can be found at https://www.npmjs.com/package/js-beautify I installed it using the command npm install js-beautify --save Next, I added the import to my app.component.ts file The documen ...

Tips for displaying a loader image with a centered message and preventing the bootstrap modal dialogue box from closing during an AJAX response from a PHP file

I am using Bootstrap version 3.0.0. Below is the HTML code for a Bootstrap Modal: <div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> < ...

Creating a script in JavaScript to execute a command or query after midnight

I have a query regarding MongoDB and JavaScript (Express.js). Here is the scenario: I am working on developing a backend service for movies and TV series. I have already set up basic routes and functions. One of my requirements is to select a movie from ...

Avoid re-rendering the template in Vue 3 with pinia when changing state values

I am utilizing Vue3 and Pinia for state management. Here is an excerpt from my Pinia file: export const useCounterStore = defineStore ({ id: 'statusData', state: () => ({ test1: 25, test2: 75 }) }) As for the template I am us ...

transfer the information from a particular key in JavaScript to Vue

Just starting out with Vue and working on a web app. I have some data in the JavaScript that includes keys like title, author, etc. I'm looking to pass the value associated with the title key to Vue. How can I achieve this? I attempted using book.tit ...

I encountered an error while attempting to integrate Vue.js into Laravel, stating: "Error: Cannot locate module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'"

https://i.sstatic.net/MivKf.png I've been implementing Vue.js into my Laravel application using the following code snippets. composer require laravel/ui php artisan ui vue npm install npm run watch-poll npm mix "--watch" "--watch-poll& ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

What is the best way to include the RethinkDB JavaScript library in EmberJS?

Having trouble using the RethinkDB javascript library in conjunction with EmberJS? With no bower package available for RethinkDB specifically for Ember, I've attempted to utilize the npm package instead. Unfortunately, I'm relatively new to the w ...

Inspect the render function in the 'RestApi' class

I encountered the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined ...

Updating the data returned by the params function in Vue.js

Here is some code that I'm working with: <template> <div> <button @click="changeData(text)">Click Me!</button> <p>{{ text }}</p> </div> </template> <script> export de ...

Restrict the size of the numerical input in AngularJS

<input class="span10" type="number" max="99999" ng-maxLength="5" placeholder="Enter Points" ng-change="myFunc($index)" ng-model="myVar"> This code snippet adjusts the value of form.input.$valid to false if the number entered exceeds 99999 or is long ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

Removing duplicate entries in child components fields using Vue JS

I am facing an issue with a child component that retrieves repeating data from an Axios request. List of Colors: blue, blue, red, orange, green, green, blue Child Component <div v-if="color"> <strong> Color:</str ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

"Enhance Your Website with Dynamic Text Effects using JavaScript

Is there a way to continuously animate text during the loading process of an AJAX request? I've tried implementing various methods, such as using a setTimeout function or an infinite loop, but nothing seems to work for repeating the animation once it& ...

Having trouble loading JSON data into a template using Vue.js

I am struggling to correctly pass JSON data into my template. I have tried multiple methods but cannot seem to get it right. If you need everything in a single code snippet, I can provide that. Thank you in advance. My HTML: <div id="app"> <col ...

I tried moving the onchange(this) function from HTML to JavaScript, but I seem to have missed a parameter. The code ends

I'm currently building a website for a fictional ice cream shop to enhance my JavaScript skills. function hideAAndB() { var pickupDiv = document.getElementById("pickupDiv"); var deliveryDiv = document.getElementById("deliveryDiv"); pickupDi ...

What is the best way to overlay a 2D text layer on top of a Three.js scene?

I have successfully created a basic 3D scene using JavaScript. The scene features a THREE.SphereGeometry paired with a THREE.MeshNormalMaterial. However, I am now faced with the challenge of adding a text layer on top of the Three.js scene. Query: What is ...