Http call-out in LWC wire function

Http call-out in LWC wire function

On April 9, 2024, Posted by , In Salesforce, With Comments Off on Http call-out in LWC wire function

Table of Contents

HTTP call-outs in a Lightning Web Component (LWC) cannot be made directly due to security restrictions enforced by Salesforce’s locker service. Instead, you need to make call-outs from the Apex controller and then wire the Apex method to the LWC. Here’s how to perform an HTTP call-out via an Apex method and wire it to an LWC:

Create an Apex Class for the HTTP Call-Out

public with sharing class HttpCalloutService {
    @AuraEnabled(cacheable=true)
    public static String makeCallout() {
        // Initialize and configure the HttpRequest
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://your-endpoint.com');
        req.setMethod('GET');

        // Send the request and handle the response
        Http http = new Http();
        HttpResponse res = http.send(req);

        if (res.getStatusCode() == 200) {
            // Handle the response content if the callout is successful
            return res.getBody();
        } else {
            // Handle errors
            throw new AuraHandledException('Callout error: ' + res.getStatus());
        }
    }
}

Wire the Apex Method to Your LWC

In your LWC JavaScript file, import the Apex method and use the @wire decorator to call it.

import { LightningElement, wire, track } from 'lwc';
import makeCallout from '@salesforce/apex/HttpCalloutService.makeCallout';

export default class YourComponentName extends LightningElement {
    @track data;
    @track error;

    @wire(makeCallout)
    wiredData({ error, data }) {
        if (data) {
            this.data = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }
}

In this code, makeCallout is wired to the LWC. The wiredData function will run whenever the Apex method returns, setting the component’s data or error properties based on the response.

Notes and Best Practices:

  • Mark the Apex method with @AuraEnabled(cacheable=true) to make it cacheable, which is a requirement for the method to be used with the @wire service.
  • Remember to handle exceptions and errors gracefully both in the Apex class and in your LWC.
  • Due to the asynchronous nature of the @wire service, your LWC should be designed to handle states where data may not yet be available.
  • Test the Apex class separately to ensure that the HTTP call-out works as expected before integrating it with the LWC.
  • Remember to add the endpoint to the list of Remote Site Settings in Salesforce Setup if it’s an external service.
Comments are closed.