Can we perform DML using wire service ?
NO, we can only receive the data and we cannot mutate/change the data using wire service.
The wire service delegates control flow to the Lightning Web Components engine. Delegating control is great for read operations, but it isn’t great for create, update, and delete operations. As a developer, you want complete control over operations that change data. That’s why you perform create, update, and delete operations with a JavaScript API instead of with the wire service. Salesforce link
It means that wire services actually deliegates the control to lwc engine, which internally perform read operation to access the data. We do not have the permission to perform DML operation using wire service.
To understand this behavior in detail, lets take a simple example of getting account information using apex method
In this example, we are trying to get the account information with given record id – using an apex method. As we know, to expose an apex method to a lightning component, we must decorate the method with @AuraEnabled (which is ofcourse the name of this website.
To access this method using wire service, we must set cacheable=true.
public with sharing class AccountRecordController {
@AuraEnabled(cacheable = true)
public static Account getSingleAccount(Id accId){
return [SELECT Id, Name, Industry
FROM Account
WHERE Id =: accId];
}
}
import { LightningElement, wire, api } from 'lwc';
import getSingleAccount from '@salesforce/apex/AccountRecordController.getSingleAccount';
export default class AccountRecordDetails extends LightningElement {
recId;
account;
errormessage;
@wire(getSingleAccount, {accId : '$recId'})
wiredSingleAccount({data, error}){
console.log(JSON.stringify(data));
console.log(data);
if(data){
this.account = data;
this.errormessage = undefined;
}else if(error){
this.account = undefined;
this.errormessage = error.body.message;
}
}
handleChange(event){
this.recId = event.target.value;
}
}
<template>
<lightning-layout horizontal-align={horizontalAlign}>
<lightning-layout-item flexibility="auto" padding="around-small">
<lightning-input label="Enter record id"
type="text"
name="recid"
value ={recId}
onchange={handleChange}>
</lightning-input>
</lightning-layout-item>
</lightning-layout>
<div class="slds-p-around_small">
<template if:true={account}>
Account Details: <br>
Name: {account.Name} <br>
Industry: {account.Industry}
</template>
<template if:true={errormessage}>
{errormessage}
</template>
</div>
</template>