I'm trying to learn to code in Apex and LWC for fun, but I'm having an issue here that I've been able to understand why:
Apex class
@AuraEnabled(cacheable=true)
public static void sellItem (String itemBarcode) {
Inventory__c item = [SELECT Id, Item_Name__c, Status__c, Item_Barcode__c
FROM Inventory__c
WHERE Item_Barcode__c =: itemBarcode];
try {
if(item.Status__c == 'Available') {
item.Status__c = 'Sold';
}
update item;
}
catch(Exception e) {
System.debug(e.getMessage());
}
}
LWC
@api itemBarcode;
@api itemToSell;
handleChange(event) {
this.itemBarcode = event.target.value;
}
@wire(sellItem, {itemBarcode: '$itemBarcode'})
wiredSellItem({error, data}){
if(data) {
this.itemToSell = data;
console.log(data);
} else if(error) {
console.log(error.message);
}
}
handleCheckOut() {
sellItem({ itemBarcode: this.itemBarcode })
.then(() => {
return refreshApex(this.itemToSell);
})
.catch(error => {
console.log('Unable to update the record => ' + error.message);
});
}
HTML
<lightning-card
title="Checkout a Book"
icon-name="standard:article"
>
<div class="slds-m-around_small">
<lightning-input
label="Item Barcode Number"
onchange={handleChange}
>
</lightning-input>
<div class="slds-m-top_x-small">
<lightning-button
label="Checkout"
variant="brand"
title="Checkout a book"
onclick={handleCheckOut}
>
</lightning-button>
</div>
</div>
</lightning-card>
When I type the item's barcode in the lightning-input I click on the button to 'sell' the item with that barcode. The problem here is that it's not updating the item's status and the console.log in the LWC component is returning the error message with 'Unable to update the record => undefined' However, when I try the Apex code on the developer console, it updates. Can anyone help me?
Thanks in advance
EDIT
@AuraEnabled(cacheable=true)
public static Inventory__c getItem(String itemBarcode){
return [SELECT Id, Item_Name__c, Status__c, Item_Barcode__c
FROM Inventory__c
WHERE Item_Barcode__c =: itemBarcode];
}
@AuraEnabled
public static void sellItem(Inventory__c item){
if(item.Status__c == 'Available'){
item.Status__c = 'Sold';
}
try {
update item;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
@wire(getItem, {itemBarcode: '$itemBarcode'}) item;
handleCheckOut() {
sellItem({ item: this.item })
.then((result) => {
console.log('SUCCESS', result);
return refreshApex(this.item);
})
.catch(error => {
console.log('Unable to update the record => ' + error.message);
});
}
error.message
is undefined, which is why you're getting that console.log. Use this resource for more information on how to debug your LWCs: developer.salesforce.com/docs/component-library/documentation/…