You need to sign in to do that
Don't have an account?
ryanschierholz
LWC. Two buttons run very similar code. How can I simplify this?
I have two buttons on a Lightning Web Component on a record page. When each is clicked, the code they run is virtually identical, so I want to reuse the code as much as possible. However, I cannot figure out the best way to do it. I can pass the button name into the code, but when I try to put the "let record + fields" code into the switch or conditional if statements, it doesnt work. I need to pass a different field name into the 'let record' statement, depending on which button is pressed.
handleActivateBuyerSide() { this.loading = true; let record = { fields: { Id: this.recordId, VirtualTCStatus_BuyerSide__c: 'Active', }, }; updateRecord(record) // eslint-disable-next-line no-unused-vars .then(() => { this.dispatchEvent( new ShowToastEvent({ title: 'Success', message: 'Record Is Updated', variant: 'success', }), ); this.loading = false; }) .catch(error => { this.dispatchEvent( new ShowToastEvent({ title: 'Error on data save', message: error.message.body, variant: 'error', }), ); this.loading = false; }); } handleActivateSellerSide() { this.loading = true; let record = { fields: { Id: this.recordId, VirtualTCStatus_SellerSide__c: 'Active', }, }; updateRecord(record) // eslint-disable-next-line no-unused-vars .then(() => { this.dispatchEvent( new ShowToastEvent({ title: 'Success', message: 'Record Is Updated', variant: 'success', }), ); this.loading = false; }) .catch(error => { this.dispatchEvent( new ShowToastEvent({ title: 'Error on data save', message: error.message.body, variant: 'error', }), ); this.loading = false; }); }
let record;
switch(buttonName) {
case button1:
record = { fields: { Id: this.recordId, VirtualTCStatus_BuyerSide__c: 'Active', }, };
break;
case button2:
record = { fields: { Id: this.recordId, VirtualTCStatus_SellerSide__c: 'Active', }, };
break;
}
updateRecord(record).then....
All Answers
let record;
switch(buttonName) {
case button1:
record = { fields: { Id: this.recordId, VirtualTCStatus_BuyerSide__c: 'Active', }, };
break;
case button2:
record = { fields: { Id: this.recordId, VirtualTCStatus_SellerSide__c: 'Active', }, };
break;
}
updateRecord(record).then....
Hi ryanschierholz,
How did you get the button name into the code? I also want to reuse the code for 2 differents buttons.