Connecting Salesforce Lightning Web Components (LWC) with external web services allows you to pull live third-party data directly into your user interface. In this step-by-step tutorial, we will build a dynamic weather component in LWC that fetches live weather forecasts based on user-entered locations using JavaScript's native fetch() API.
Prerequisites
- Basic understanding of JavaScript ES6 (
async/await, Promises, and object destructuring) and LWC structure. - An active Salesforce Developer org or Sandbox instance.
- An API key from a free weather data provider such as WeatherAPI.com or OpenWeatherMap.
Step 1: Set Up the Project
Create a new Lightning Web Component in your project workspace using Visual Studio Code or execute the following Salesforce CLI command in your terminal:
sf force lightning component create --type lwc --componentname WeatherComponent --outputdir force-app/main/default/lwc
Step 2: Define Component Template Markup
Open WeatherComponent.html and build the input form along with conditional rendering elements to display weather metrics:
<!-- WeatherComponent.html -->
<template>
<lightning-card title="Weather Information" icon-name="utility:frozen">
<div class="slds-m-around_medium">
<lightning-input
label="Enter Location"
value={location}
onchange={handleLocationChange}>
</lightning-input>
<div class="slds-m-top_medium">
<lightning-button
label="Get Weather"
variant="brand"
onclick={getWeatherData}>
</lightning-button>
</div>
</div>
<template if:true={weatherData}>
<div class="slds-m-around_medium slds-box">
<p><strong>Location:</strong> {weatherData.location}</p>
<p><strong>Temperature:</strong> {weatherData.temperature}°C</p>
<p><strong>Condition:</strong> {weatherData.condition}</p>
</div>
</template>
</lightning-card>
</template>
Step 3: Implement Asynchronous JavaScript API Call
Open WeatherComponent.js and implement the asynchronous API call using fetch() inside an async handler method:
// WeatherComponent.js
import { LightningElement, track } from 'lwc';
export default class WeatherComponent extends LightningElement {
@track weatherData;
location = '';
handleLocationChange(event) {
this.location = event.target.value;
}
async getWeatherData() {
if (!this.location) {
return;
}
const apiKey = 'YOUR_API_KEY'; // Replace with your WeatherAPI key
const endpoint = `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${encodeURIComponent(this.location)}`;
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error('Failed to retrieve weather data');
}
const data = await response.json();
this.weatherData = {
location: data.location.name,
temperature: data.current.temp_c,
condition: data.current.condition.text
};
} catch (error) {
console.error('Error fetching weather metrics:', error);
this.weatherData = undefined;
}
}
}
https://api.weatherapi.com!
- HTTP Client: Uses browser-native
fetch()API wrapped in asynchronousasync/awaitlogic. - State Tracking: Employs reactive tracking (
@trackor reactive properties) to update template renders upon data fetch. - Salesforce Security: Requires domain whitelisting under CSP Trusted Sites before initiating client-side API requests.
Conclusion
Integrating third-party APIs into Lightning Web Components unlocks versatile capabilities for your Salesforce org. By combining LWC input directives with native JavaScript fetch() methods, you can seamlessly integrate real-time external data streams directly into standard platform layouts.