Reputation: 403
I think my question is fairly simple. I have these 2 buttons:
<button @click="getPartyLeader" class="btn btn-success">Get party leader</button>
<button @click="saveParty" class="btn btn-success">Submit</button>
I don't want the user to have to click on the get party leader
button first and after that on the submit button. Is it possible to combine these buttons so that the getPartyLeader
method is executed first and the saveParty
method is executed when the first one is done?
My javascript In case you need it:
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 already tried to do this.getPartyLeader
at the start of the saveParty()
method, but that was not successful.
Can anyone help? Thanks!
Upvotes: 0
Views: 76
Reputation: 2373
The reason its not working is your getPartyLeader
method has an asyn component which you are not awaiting. I think the code you need is
async saveParty() {
await this.getPartyLeader()
... // the rest of the method
},
async getPartyLeader(){
var leadername = this.leaderName;
// Note returning 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);
});
}
}
I'm assuming PartyLeaderDataService.findByName(leadername)
returs a Promise
Upvotes: 1