Connect Apex with Lwc Using @wire - Salesforce
Tags: salesforce, lwc, javascript, beginners
Published: 2021-10-24 12:48:21

## @wire

`@wire` is basically used to fetch salesforce data using `apex` or `uiRecordApi` etc.
The wire service provisions an immutable stream of data to the component.
**Note :** Objects passed to a component are read-only. To mutate the data, a component should make a shallow copy of the objects it wants to mutate. [More Details](https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_components_data_flow.html "To prevent code complexity and unexpected side effects, data should flow in one direction, from parent to child.").

### Syntax:
1. We need to import `wire` from `lwc`
```javascript
import { LightningElement, wire} from  'lwc';
```
2.  We need to import our `apex` method from apex class using below syntax:
```javascript
import apexMethodName from  '@salesforce/apex/Namespace.ApexClassName.MethodName';
```
3. we need `@wire` to call our apex function using below syntax inside our default class:
```javascript
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;
```


## Example:


**Apex class :** 
```java
public class AccountHelperClass {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name FROM Account];
    }
}
```
**Note:** In `Apex Class`, the function you want to call in lwc `.js` file, the function should be `@AuraEnabled`  **and you must set `cacheable=true`** in case of `@wire` in lwc.

>  Marking a method as cacheable improves your component’s performance
> by quickly showing cached data from client-side storage without
> waiting for a server trip. If the cached data is stale, the framework
> retrieves the latest data from the server. Caching is especially
> beneficial for users on high latency, slow, or unreliable connections.
> Cacheable methods perform better, so use them when possible.

**Js File :**

```javascript
import { LightningElement, wire} from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
@wire(getAccountList) accountList; // directly storing data into variable/property
}
```
**Note :** In above function the data from `AccountHelperClass.getAccountList` will be stored in  `accountList`. 

> The `@wire` basically store two object in the prefered property name like in above example, It will store `data` and `error` in `accountList`. So you can use the **data** using **`accountList.data`** and **error** using **`accountList.error`.**
>
**IMPORTANT :**
If your Apex Method doesn't require input variables like the above apex method `getAccountList`, you can simple call apex method like the above one But if it requires input variables like below method
 
```java
public class AccountHelperClass {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList(Integer noOfEmployees, Boolean emailRequired) {
        return [SELECT Id, Name FROM Account ];
    }
}
```
In `JS` file you can simply pass value to Apex method input variable by using same name as mentioned in your apex function like below :
```javascript
@wire(getAccountList, {noOfEmployees : 5, emailRequired : true }) accountList; 
```
### wire with function :
If you want to store the `data` and `error` in different variables you can use function and local variable in your js file like below:
```javascript
import { LightningElement, wire, track} from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
	@track record;
    @track error;
@wire(getAccountList) 
/* Here the data and error will be directly pass 
from apex function to wiredAccount function 
and you can name this function as per your choice
*/
wiredAccount({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }
}
```

### USAGE :

 - HTML File :
 ```html
<template>
<lightning-card  title="Call Apex From LWC"  icon-name="custom:custom63">
	<div  class="slds-m-around_medium">
		<template  if:true={accountList.data}>
			<template  for:each={accountList.data} for:item="acc">
				<p  key={acc.Id}>{acc.Name}</p>
			</template>
		</template>
		<template  if:true={accountList.error}>
			Error: {accountList.error}
	 	</template>
	</div>
</lightning-card>
</template>
 ```
- JS File :
```Javascript
import { LightningElement, wire} from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
@wire(getAccountList) accountList;
}
```
**OR**
 - HTML File :
 ```html
<template>
<lightning-card  title="Call Apex From LWC"  icon-name="custom:custom63">
	<div  class="slds-m-around_medium">
			<template  for:each={record} for:item="acc">
				<p  key={acc.Id}>{acc.Name}</p>
			</template>
				<template  if:true={error}>
			Error: {error}
	 	</template>
	</div>
</lightning-card>
</template>
 ```
 - Js File :
 ```javascript
import { LightningElement, wire, track} from  'lwc';
import getAccountList from  '@salesforce/apex/AccountHelperClass.getAccountList';
export  default  class  IterationComp  extends  LightningElement {
	@track record;
    @track error;
@wire(getAccountList)
wiredAccount({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }
}
```

Result :
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdldxkvbkrdp0mujka15.png)

### Disadvantage of `@wire` :

 - Can't control over its run, The function is invoked whenever a value is available, which can be before or after the component is connected or rendered.
 - Can't mutata data in apex function as it use `cacheable=true`.

### Advantages of `@wire` :
- More faster than Imperative call.
- Can be referesh data by using `refreshApex()`.
- More useful in case of using `uiRecordApi`.