Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to delete them individually using separate Axios calls.

After this process is complete, I am in need of executing some code to refresh the page. How can I accomplish this task in a straightforward manner? Where should I position my code for refreshing the content?

Below is the current status of my code implementation:

deleteCommentAxiosCall (id) {
  return this.$axios.delete(`/api/v1/comment/${this.comment.id}`)
},
deleteComment () {
  return new Promise((resolve, reject) => {
    this.deleteCommentAxiosCall(this.comment.id)
    if (this.comment.child_comments.length) {
      this.comment.child_comments.forEach((child) => {
        this.deleteCommentAxiosCall(child.id)
      })
    }
  })
  window.location.reload() // code for refreshing the page

Answer №1

To ensure the deletions are resolved before refreshing, you can chain promises together. Utilize Promise.all() to await multiple promises simultaneously. In this scenario, you would await the deletion of the main comment along with its child comments.

deleteComment () {
  return Promise.all([
    this.deleteCommentAxiosCall(this.comment.id),
    this.comment.child_comments.map(child => this.deleteCommentAxiosCall(child.id))
  ])
  .then(() => window.location.reload())
}

Alternatively, you can use an async function:

async deleteComment () {
  await Promise.all([
    this.deleteCommentAxiosCall(this.comment.id),
    this.comment.child_comments.map(child => this.deleteCommentAxiosCall(child.id))
  ])
  window.location.reload()
}

Additionally, reloading the page may disrupt the user experience. Consider a smoother approach by refreshing the comments with an explicit API request. For example:

this.$axios.get(`/api/v1/comments`).then(resp => this.comments = resp.data.comments)

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

How can one retrieve every element within nested associative arrays?

Situation : Upon receiving a JSON array from a jQuery <-> PHP Ajax request, the unparsed JSON array structure appears as follows: {"Focus":{"id":2,"brand":"Ford","name":"Focus"}} Upon using JSON.parse(json);, the structure transforms to: Foc ...

"Utilizing JSON information to create visually appealing graphs and charts

Struggling with syntax and in need of assistance. I have a basic data set that I want to display as a timeline with two filled lines (Time Series with Rangeslider). This is the format of my data set: [{"pm10": 12.1, "pm25": 7.0, "time": "13.08.2018 12:25 ...

Is there a way to incorporate a Laravel foreach loop within a JavaScript file?

I recently added a select-box using jQuery: <span onclick="createProduct()">Add New<i class="fa fa-plus"></i></span> <script> function createProduct() { var html = ''; html += ' <div clas ...

Activate the mandatory attribute once the checkbox associated with the field is selected

I am facing an issue with looping rows that contain checkboxes and dropdown lists. I want the dropdown list to be marked as required when its corresponding checkbox is selected in each row. MARK NAME QUANTITY ------------- ...

Using surge.sh to deploy a Vue project

All day I've been attempting to deploy my Vue project on Surge.sh. The project is built using the webpack-simple template. Strangely, manual deployment from my CLI works fine. However, when I push it to GitHub and try deploying it from Travis CI, it ...

Press the button to access the URL within the current window

Working with Angular, I attempted to develop a function to open a URL in the current window. However, the code below within the controller actually opens a new window: $scope.openUrl = function(url) { $window.open(url); }; ...when using ng-click=&apo ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

Ways to contact a .aspx method from a .cs file

My web page includes JavaScript in the .aspx file for a save button. The source code declares a function called OnClientClick="javascript: validateTextTest()", and this function is called in the head of the source code using validateTextTest(). Here is th ...

Tips for preventing duplicate Java Script code within if statements

In my function, there are various statements to check the visibility of fields: isFieldVisible(node: any, field: DocumentField): boolean { if (field.tag === 'ADDR_KOMU') { let field = this.dfs_look(node.children, 'ADDR_A ...

Invoker of middleware and stack functions for Express.js with a focus on capturing the response object

It appears that the expressjs app contains a stack of Layer object Arrays. What function is utilized to pass the I am curious about: When a request is sent from the http client, which function is called first and how are the stack array functions with mi ...

Looping Feature in Ionic Framework's Slides Component

Currently, I am working on developing an application using Ionic-Angular. When it comes to incorporating slides in my app, I opted for the ionic 4 ion-slides component. Everything was going smoothly until I wanted to enable looping for the slides so that u ...

Guide to Displaying HTTP POST Request Response on Pug Template

Whenever a user interacts with the form, I initiate an HTTP POST request to the database server. Subsequently, the database server sends a POST request back to the user's server. The issue I am facing is the inability to display this database result ...

Updating parameters in Node.js with mongoose

script.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var scriptSchema = new Schema({ status: {type: String, default: 'INCOMPLETE'}, code: String, createdDate: {type: Date, default: Date.now}, user: {t ...

Put dashes in the middle of each MongoDB post title

In my express app, users can create and view posts. Currently, I search for posts by their title. However, I am encountering an issue when the post title contains spaces. The search function works perfectly for titles without spaces, but it gives an error ...

Error in Node.js: Using `import` token incorrectly

I am having trouble figuring out what the issue is. Node v5.6.0 NPM v3.10.6 This is the code snippet: function (exports, require, module, __filename, __dirname) { import express from 'express' }; The error message reads: SyntaxError: Une ...

Encountering an issue with the date pipe in Angular that prevents

I'm trying to incorporate a date pipe in my AngularJS and Firebase project to display the creation date of a post. However, I am facing an issue where the date does not appear when testing it. Below is my create Post function: createPost() { con ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Unable to retrieve accurate information

I am currently in the process of developing an application that utilizes Spring Boot and ReactJS. I encounter an issue where, despite entering correct data values in the form on the client side using the POST method, the response displays NULL values. Upo ...

Are there any methods for updating redux-form's submitting property with a workaround?

I have integrated reCAPTCHA v2 with a sign-up form that is using redux-form. The issue I am facing is that when the user submits the form, the reCAPTCHA modal pops up and the redux-form's 'submitting' prop changes from 'false' to & ...

What happens if you try to add a member to a Mailchimp list who is already on the list

After following Angela Yu's course for the past few weeks, I attempted to implement the Mailchimp API as she demonstrates. However, I encountered difficulties due to recent changes in Mailchimp. Despite this setback, I was able to find the API referen ...