How To Fetch And Display Record Data In Lightning Web Component| LWC | @wire | Salesforce

fetch and display data in lwc | salesforce


How To Fetch And Display Record Data In LWC

Hello kid πŸ‘ΆπŸ», after a long vacation let's get started with new learning sessions. These days are crazy and you know it.

In the previous EPISODE, we discussed how we can pass data from child component to parent with the help of events.

In this episode, we are going to learn methods to fetch data and different ways to display it. This will be your one-stop for all the queries regarding fetching and displaying data in the lightning web component in the easiest way possible.

So for all of that and more let's get started...

There are two major learning aspects for this episode i.e. WHAT and WHY.

WHAT - What exactly each terminology/decorator mean.
WHY - Why we are using it.

If these two W's are clear to you. You can climb mountains in future easily.

Now there are two different concepts we are going to cover here first is different ways of fetching the data and the second one is different ways of displaying that data.

Let's discuss about ways of fetching data.

FETCHING DATA :
     

WAYS OF FETCHING DATA :

salesforceServerClient



Before starting out with the ways let's first understand how this mechanism works.

Let's consider an example of you are going for fishing 🎣 today. Whenever you want to get the fish 🐟 from water πŸŒŠ you will just use your fishing rod 🦯 and a hook πŸͺ to catch a fish from water. Once you received the expected fish you store that in your fish basket πŸ§Ί

So that whenever you want that fish, you will just have to pick one 🐟 from the fish basket 🧺. I don't really go for fishing, anyways πŸ€”. 

Now from the above scenario :
- Water 🌊 is SERVER
- Fish 🐟  is Data
- Fishing rod πŸŽ£ is tool i.e. @wire in our case for lwc.
- Fish basket πŸ§Ί is a client-side cache in our case for lwc.

Now let's talk about different ways to understand this in more detail.

There are two major ways we can fetch the data from server-side controller (apex controller)

1. Direct Binding (@wire to a property)
2. Using Promises (@wire as a function)

In both ways, we are trying to fetch the records from the server-side controller (Apex) to our client-side controller(component javascript).

In both of the above ways, we are going to use the @wire property to fetch the data. Please note that the data you are trying to fetching with the help of these methods is immutable, which means you can read that data, but you will not be able to modify that.

Let's understand this more clearly with the help of code.

Let's talk about the apex controller first :

Apex Controller :
===========
public with sharing class getRecordDataController {
//@AuraEnabled is annotation enables LWC to access below apex method
//(cacheable=true) is for caching the data on client side storage without
   waiting for server trips. Which imporves the performance
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Phone FROM Account];
}
}
===========

In the above class, if you are familiar with lightning aura components, you might have already used the @AuraEnabled annotation, enabling the method to be used in the lightning components.

Now, this time we have (cacheable=true) additional which is nothing but the 🧺 basket we have learned when understanding the concept at the beginning of this episode to store the cache on the client-side.

And yes the method is returning the list of Accounts as you are smart enough now to understand that kid 😎.

So what's next on our list ?? js..js..js ? Yess 

As this part is about fetching the data we will be talking about javascript (client-side controller) before the .HTML markup file as we will be discussing this in displaying data section.

getDataDisplayData.js :
===============
import { LightningElement, wire} from 'lwc';
import getAccounts from '@salesforce/apex/getRecordDataController.getAccounts';

export default class GetDataDisplayData extends LightningElement {
@wire(getAccounts) wiredAccounts;
}
===============

In the above code, the first highlighted line will import the method which we have created and you can give any variable name just like I have given it as getAccounts.

Next, we have used @wire property to wired the getAccount to wiredAccounts so that we can use this whenever we want to use it further. One thing to be noticed here is we need to append wiredXXX when wiring to the property. This is a direct binging method.

Now, let's take a look at the next way of fetching the data on the client-side which is using javascript promises.

Quick intro about promises, this is just like you promise your mother that you will go to market and come back with the groceries requested (I was talking about true promises πŸ€ͺ). Now there can be two outcomes of it either you will come back with requested groceries or you may face issues for example, the store was closed, you forgot wallet at home etc.

Similarly, javascript promises works, when you use promises there can be two outcomes of it:
1. Either you will get the request data from the server.
2. There can be error when trying to get the data.

Let's check this with the help of code as below :

getDataDisplayData.js :
===============
import { LightningElement, wire} from 'lwc';
import getAccounts from '@salesforce/apex/getRecordDataController.getAccounts';

export default class GetDataDisplayData extends LightningElement {
//Method 2
@wire (getAccounts) wiredAccounts({data,error}){
if (data) {
console.log(data);
} else if (error) {
console.log(error);
}
}
}
===============

As you can see in the above method, we are just using javascript promises as an extra piece of code πŸ§‘‍πŸ’». Here we have better control over the returned data on the outcome. As simple as if we get the data use that data or if we get error display that error.
For testing you can add this component in you lightning application and check the browser console logs if you are getting data or not before displaying it.

NOTE: Please note that in both cases it will store the data/error. Hence we can use it as wiredAccounts.data or wiredAcconts.error as we will be using in upcoming displaying the data part.

Developer Console[www.sfdckid.com]


There we go..we can see all the accounts console logs.

Now let's take a look at the most exciting part of displaying the data.

DISPLAY DATA :

Now, once you have the material to construct the house you can always design and display that as per your need. It is as important as fetching the data.

Now as we have already seen in the previous episode how to display the data when we have a list of records to display.

Now its totally depends on your imagination of displaying this data.

Let's take a look at the very basic way of it and then we will go a little advance.

Displaying it as list :

Now as you know we have all our data wired to wiredAccounts hence we will be using the data from it.

If you remember the method 1 :

//Method 1
@wire(getAccounts) wiredAccounts;

If you want to display the data of this method in the list then we will be iterating it with for:each like this :

getDataDisplayData.html :
======
<template>
<template for:each={wiredAccounts.data} for:item="acc">
<p key={acc.id}>
{acc.Name}
</p>
</template>
</template>
=====

And the output will look like this :

Output :
=====
OutputLWC
=====

Now, let's suppose you want to display the data into data table using the second way of fetching the data i.e. using js promises.

You need to modify and assign the value of data a bit and define columns so fo datatable example.

Let's have a look at .JS file. After modification it will look like this :

getDataDisplayData.js :
===============
import { LightningElement, track, wire} from 'lwc';
import getAccounts from '@salesforce/apex/getRecordDataController.getAccounts';

export default class GetDataDisplayData extends LightningElement {
@track columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Id', fieldName: 'Id'}
];
@track accountList;

//Method 2
@wire (getAccounts) wiredAccounts({data,error}){
if (data) {
this.accountList = data;
console.log(data);
} else if (error) {
console.log(error);
}
}
}
===============

And after adding lightning datatable to our HTML file it will look like this:

getDataDisplayData.html :
=================
<template>
<div style="height: 500px;">
<template if:true={accountList}>
<lightning-datatable
key-field="id"
data={accountList}
columns={columns}>
</lightning-datatable>
</template>
</div>
</template>
=================

and the final output of above code will be :

Output :
======
lwcDatatable
======

Yaay!! Now you can display this data as beautiful as your girlfriend 

Let's take some samples I have created for you :

1) If you want to display the same data as the badge tag :

your HTML file will look like this :
====
<template>
<div class="slds-grid slds-wrap">
<template for:each={accountList} for:item="acc">
<span key={acc.id}>
<div class="slds-col slds-size_3-of-12">
<lightning-badge label={acc.Name}></lightning-badge> &nbsp;
</div>
</span>
</template>
</div>
</template>
====

Output :
====
output
====

2) Display as a checkbox :
=====
<template>
<div class="slds-box">
<template for:each={accountList} for:item="acc">
<span key={acc.id}>
<div class="slds-col">
<lightning-input type="checkbox" label={acc.Name} ></lightning-input>
</div>
</span>
</template>
</div>
</template>
=====

Output :
=====
output
=====

Yay!! Kid πŸ’ƒ, now you are good to go and play around with this. 

Now next time when your senior ask questions like why do we use (cacheable=true) throw that fishing basket example to them. If someone asks how many ways we can use wire to get the data to throw the examples to them and finally if some ask you how to fetch and display the data throw this blog link into their inbox πŸ“₯.

Now some special part of fetching the data :

1) Get the recordId of current record. Then you can directly do that by 

STEP 1 : Add below lone of code inside your .JS file (on top)

- > import { getRecord } from 'lightning/uiRecordApi';

STEP 2 : Declararing default variable recordId

- > @api recordId;

Now, you can directly use this recordId to perform further logic on current record as required.

2) Get object data :
Although we have learned about the fetching the account object data using server call but if you do not want any filtered data then you can use below piece of code directly without writing apex controller by using schema :

Import object using below syntax inside your .js file :

-> import objectName from '@salesforce/schema/object';

Replace object with your object API name.

for example : 

import ACCOUNT_OBJECT from '@salesforce/schema/Account';

Now you can use this ACCOUNT_OBJECT directly. Also please note that please use naming convention for objects as OBJECTNAME_OBJECT. 

3) Get field data :
Similar to object data we can also fetch the particular field directly from schema inside lwc component.

Please find the below syntax which can be use to import the field from the object :

import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';

Here as well we need to follow the naming convention as FEILDNAME_FEILD similar to object.

Now, the purpose of this is to directly bing these fields and recordId and get the value using @wire adoptor in salesforce lightning web component.

Want to see how ?

For example :
=========
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';

export default class GetDataDisplayData extends LightningElement {
//This is how you will bind your recordId and fields
@wire(getRecord, { recordId: '$recordId',fields: ACCOUNT_NAME_FIELD })
    accountData;

//Now if you want to access Account Name of current record then simply you can use it for example :

 get accName(){
// This is how you will get the value 
 return accountData.data.fields.Name.value;
 }
}
=========

This way you can also display only specific data as per your requirement. You need to play with all the ways we discussed in episode to get better and better when playing with the data. 

In the upcoming episode we will try to create mini project modules with salesforce LWC components and the boss level challenging components as well. So all of that see you in the next episode. Till then keep learning...keep growing and keep sharing.

WOHOOO !! YOU HAVE JUST COMPLETED HOW TO FETCH AND DISPLAY DATA IN LWC EPISODE
If you like this SFDCkid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all ⚡️Happy Learning ☁️⚡️ (Learn. Help. Share.) πŸ˜Š 


sfdckidFooter

How To Fetch And Display Record Data In Lightning Web Component| LWC | @wire | Salesforce How To Fetch And Display Record Data In Lightning Web Component| LWC | @wire | Salesforce Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.