Today, we are going to understand how we can make callouts directly from LWC. In Salesforce, we only use Apex to make calls to an external system for Integration. But in some scenarios, we are not able to make callouts in Apex like you are uploading a large-size file. So, you are using LWC in the front end & getting the content in JS, and then passing the content of the file as a string in apex. It will give you an error of Heap Size Limit.
In those scenarios, We need to make callouts directly from JS. So, It will work perfectly for your different scenario. Let's go in-depth and understand how can we make callouts:
Firstly, We need to set up a CST Trusted Site definition in Salesforce.
Also Read: Connect Dropbox with Salesforce using REST API
CSP Trusted Sites
<template> | |
<lightning-card title="Chunk Norries - Random Jokes"> | |
<lightning-layout> | |
<div class="slds-p-around_small"> | |
<lightning-button variant="brand" | |
label="Generate Random Chunk Jokes" | |
onclick={handleClick}> | |
</lightning-button> | |
<br> | |
<template if:true={jokeReady}> | |
<p>{randomJoke}</p> | |
</template> | |
<template if:true={loadingSpinner}> | |
<lightning-spinner alternative-text="Loading" variant="inverse" size="medium"></lightning-spinner> | |
</template> | |
</div> | |
</lightning-layout> | |
</lightning-card> | |
</template> |
import { LightningElement } from 'lwc'; | |
export default class ChunkNorriesAPI extends LightningElement { | |
jokeReady = false; | |
loadingSpinner = false; | |
randomJoke; | |
handleClick(){ | |
this.loadingSpinner = true; | |
this.jokeReady = false; | |
fetch('https://api.chucknorris.io/jokes/random', {method: 'GET'}) | |
.then(response => response.json()) | |
.then(data => { | |
console.log('--JSON-- '+JSON.stringify(data)); | |
this.randomJoke = data.value; | |
this.jokeReady = true; | |
this.loadingSpinner = false; | |
}); | |
} | |
} |
<?xml version="1.0"?> | |
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"> | |
<apiVersion>55.0</apiVersion> | |
<isExposed>true</isExposed> | |
<targets> | |
<target>lightning__HomePage</target> | |
</targets> | |
</LightningComponentBundle> |
Comments