Is it possible for you to execute 2 procedures consecutively simply by clicking on a button?

My question is quite straightforward. I have two buttons:

<button @click="getPartyLeader" class="btn btn-success">Get party leader</button>
  <button @click="saveParty" class="btn btn-success">Submit</button>

I want to streamline the process so that the getPartyLeader method runs first and then the saveParty method executes automatically afterwards. Is there a way to combine these buttons to achieve this?

Here is my JavaScript:

import PartyDataService from "@/services/PartyDataService";
import PartyLeaderDataService from "../../services/PartyLeaderDataService";

export default {
  name: "AddParty",
  data() {
    return {
      leaderName: "",
      party: {
        id: null,
        name: "",
        description: "",
        ispartynational: true,
        partyLeader: {id: null, name: "", appearance: ""}
      },
      message:"",

    };
  },
  methods: {
    saveParty() {
      var data = {
        name: this.party.name,
        description: this.party.description,
        ispartynational: true,
        partyLeader: {
          id: this.party.partyLeader.id,
          name: this.party.partyLeader.name,
          appearance: this.party.partyLeader.appearance
        }
      };
      PartyDataService.create(data)
          .then(response => {
            this.party.id = response.data.id;
            console.log(response.data);
            this.message = 'The Party was created successfully!';
          })
          .catch(e => {
            console.log(e);
          });
    },
    newParty() {
      this.party = {};
    },
    getPartyLeader(){
      var leadername = this.leaderName;
      PartyLeaderDataService.findByName(leadername)
      .then(response => {
        this.party.partyLeader.id = response.data.id
        this.party.partyLeader.name = response.data.name
        this.party.partyLeader.appearance = response.data.appearance
        console.log(this.party)
      })
          .catch(e => {
            console.log(e);
          });
    }
  }
}

I attempted to call this.getPartyLeader at the beginning of the saveParty() method without success. Any help would be greatly appreciated. Thank you!

Answer №1

If your code is not functioning properly, it could be due to the fact that your getPartyLeader method includes an asynchronous component that is not being awaited. Here's a suggested update for your code:

async saveParty() {
    await this.getPartyLeader()
    ... // continue with the rest of the method
},
async getPartyLeader(){
      var leadername = this.leaderName;
      // Make sure to return the promise
      return PartyLeaderDataService.findByName(leadername)
      .then(response => {
        this.party.partyLeader.id = response.data.id
        this.party.partyLeader.name = response.data.name
        this.party.partyLeader.appearance = response.data.appearance
        console.log(this.party)
      })
          .catch(e => {
            console.log(e);
          });
    }
}

It is assumed that

PartyLeaderDataService.findByName(leadername)
yields a Promise.

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

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

problem with passing the identification number into the function

I am facing an issue with passing the id into a javascript onClick method. I am using the Spring framework and in the controller class, I send the related id to the JSP file like this: model.addAttribute("uploadid", uploadid); Afterwards, I need to p ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

The bootstrap modal is appearing correctly, but the content within it is not displaying properly

I've been working on a website and added a modal for signup. However, when the user clicks on the signup button, the modal appears but the content inside it is not clickable. Can someone please help me with this issue? Here is the code snippet I am us ...

Update the sum upon deleting a feature in an HTML and JavaScript form

Once a row or field is added, this function will display a delete link. When clicked, it will remove the row or field: var ct = 1; function addNewRow(){ ct++; var divElement = document.createElement('div'); divElement.id = ct; // Code to cr ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Tips for incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

JavaScript array error - unrecognized symbol

Hello, I am attempting to generate an array of errors and showcase them all at once. Here is my code: if (!first_name) { var error[] = "Please fill in the Last Name"; $('#first_name').addClass('error'); } else { $('#fi ...

JavaScript Routing with Multiple Files

I tried to access api.js from Routes.js, but I encountered an issue stating that the function my_function_in_api is not defined. Here is my code, could you please help me identify where the problem lies: Routes.js var val = require('file name') ...

What is the best way to update my logo and incorporate a colored border at the bottom of my fixed header while the user is scrolling down?

After spending countless hours researching online, I've been struggling to implement header effects on scroll without using JavaScript. My goal is to achieve a simple effect where the header reduces in height, the logo changes, and a colored border is ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

Ways to retrieve textStatus beyond ajax boundaries

Do you know how to access the textStatus variable after an ajax call? I need to use this variable in an if condition. Can anyone provide assistance? $this->registerJs("colorArray = ['#ff4c4c','#32CD32']; $('.grooveTable&apo ...

What is the best way to distinguish between various objects that are all in a single line?

After creating an array of objects with data such as name and id, I used the res.json() method to convert it into json format for browser use. However, when I input the array of object data, it looked like this: [ { id: 1, name: 'albany sof ...

The method for retrieving and entering a user's phone number into a text field upon their visit

Objective: To enhance the user experience by automatically filling in the phone number input field when a mobile user views the page, making it easier to convert them into leads. A privacy policy will, of course, be in place. This page will offer a promo ...

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

tips for converting a single observable item into an observable list

Within my Angular project, there exists an observable object with the following structure: export interface FavoritesResponse { wallet: boolean; deposit: boolean; withdraw: boolean; transfer: boolean; exchange: boolean; ticket: boolean; accou ...

Utilizing a drop-down menu in AngularJS to dynamically change a URL and fetch images

Currently, I am in the process of creating a website using AngularJS that accesses images from reddit and showcases them based on various parameters such as number of votes and date posted. While this is not groundbreaking, my main goal is to enhance my sk ...